Module: Embedded::Model
- Defined in:
- lib/embedded/model.rb
Constant Summary collapse
- ScopeMethod =
ActiveRecord::VERSION::MAJOR >= 4 ? :all.freeze : :scoped.freeze
Instance Method Summary collapse
- #embedded ⇒ Object
- #embedded_attributes ⇒ Object
- #embedded_column_names(embeddable_attr, attributes) ⇒ Object
- #embeds(embeddable_attr, options = {}) ⇒ Object
Instance Method Details
#embedded ⇒ Object
17 18 19 |
# File 'lib/embedded/model.rb', line 17 def Embedded::Scope.new(send(ScopeMethod),) end |
#embedded_attributes ⇒ Object
21 22 23 |
# File 'lib/embedded/model.rb', line 21 def @embedded_attributes ||= {} end |
#embedded_column_names(embeddable_attr, attributes) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/embedded/model.rb', line 5 def (, attributes) if attributes.is_a?(Array) attributes.inject({}) do |hash, a| hash.merge(:"#{}_#{a}" => a) end elsif attributes.is_a?(Hash) attributes.invert else raise ArgumentError.new('invalid attributes') end end |
#embeds(embeddable_attr, options = {}) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/embedded/model.rb', line 25 def (, = {}) self.[] = attributes = [:attrs] columns = (,attributes) clazz = [:class_name] ? [:class_name].constantize : .to_s.camelcase.constantize self.send(:define_method, ) do values = columns.inject({}) do |hash,(k,v)| hash.merge(v=>read_attribute(k)) end clazz.new(values) end self.send(:define_method, :"#{}=") do |v| if v.is_a?(clazz) columns.each do |k,a| write_attribute(k, v.send(a)) end elsif v.is_a?(Hash) columns.each do |k,a| write_attribute(k, v[a]) end else raise ArgumentError.new("invalid class. #{clazz.to_s} or Hash was expected") end end end |