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

Instance Method Details

#embeddedObject



11
12
13
# File 'lib/embedded/model.rb', line 11

def embedded
  Embedded::Scope.new(send(ScopeMethod),embedded_attributes)
end

#embedded_attributesObject



15
16
17
# File 'lib/embedded/model.rb', line 15

def embedded_attributes
  @embedded_attributes ||= {}
end

#embedded_column_names(embeddable_attr, attributes) ⇒ Object



5
6
7
8
9
# File 'lib/embedded/model.rb', line 5

def embedded_column_names(embeddable_attr, attributes)
  attributes.inject({}) do |hash, a|
    hash.merge(:"#{embeddable_attr}_#{a}" => a)
  end
end

#embeds(embeddable_attr, options = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/embedded/model.rb', line 19

def embeds(embeddable_attr, options = {})
  self.embedded_attributes[embeddable_attr] = options

  attributes = options[:attrs]
  columns = embedded_column_names(embeddable_attr,attributes)
  clazz = options[:class_name] ? options[:class_name].constantize : embeddable_attr.to_s.camelcase.constantize

  self.send(:define_method, embeddable_attr) do
    values = columns.inject({}) do |hash,(k,v)|
      hash.merge(v=>read_attribute(k))
    end
    clazz.new(values)
  end

  self.send(:define_method, :"#{embeddable_attr}=") do |v|
    columns.each do |k,a|
      write_attribute(k, v.send(a))
    end
  end
end