Skip to content

Instantly share code, notes, and snippets.

@slowjack2k
Created June 27, 2014 09:53
Show Gist options
  • Save slowjack2k/a0c01fce4c7e40eb6079 to your computer and use it in GitHub Desktop.
Save slowjack2k/a0c01fce4c7e40eb6079 to your computer and use it in GitHub Desktop.
module BaseEntity
extend ActiveSupport::Concern
include ActiveModel::Model
include ActiveModel::Dirty
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
included do
include ::Virtus.model
include OverrideAttributes
attribute :id, Integer
extend ActiveModel::Translation
end
module OverrideAttributes
extend ActiveSupport::Concern
def attributes(*)
super.each_with_object({}) { |(key, value), new_hash| new_hash[key.to_s] = value }
end
module ClassMethods
def attribute(attr_name, *new_properties)
super
define_attribute_methods attr_name
method_str = <<-"EOF_M"
def #{attr_name}=(new_value)
#{attr_name}_will_change! unless new_value == attribute_set[:#{attr_name}].get(self)
super
end
EOF_M
class_eval method_str, __FILE__, __LINE__ + 1
end
end
end
def reset_changes_flag
@previously_changed = changes
@changed_attributes.clear
end
def reset_changes!
changed_attributes.keys.map { |attr| public_send("reset_#{attr}!") }
end
module ClassMethods
def model_name=(new_name)
@_model_name = new_name
end
def model_name
@_model_name ||= model_name_without_namespace
end
def model_name_without_namespace
name = ActiveSupport::Inflector.demodulize(self)
ActiveModel::Name.new(self, nil, name)
end
attr_writer :i18n_scope
def i18n_scope
@i18n_scope ||= :activemodel
end
def _to_partial_path
@_to_partial_path ||= begin
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
collection = ActiveSupport::Inflector.tableize(model_name_without_namespace)
"#{collection}/#{element}".freeze
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment