Module: Faceted::Model::ModelClassMethods

Defined in:
lib/faceted/model.rb

Overview

Class methods ============================================================

Instance Method Summary collapse

Instance Method Details

#build_association_from(field) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/faceted/model.rb', line 12

def build_association_from(field)
  bare_name = field.gsub(/_id$/, '')
  if field =~ /_id$/
    klass = eval "#{scope}#{bare_name.classify}"
    fields << bare_name.to_sym
    define_method :"#{bare_name}" do
      klass.new(:id => self.send(field))
    end
  end
end

#create(params = {}) ⇒ Object



23
24
25
26
27
# File 'lib/faceted/model.rb', line 23

def create(params={})
  obj = self.new(params)
  obj.save
  obj
end

#field(name, args = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/faceted/model.rb', line 29

def field(name, args={})
  fields << name
  define_method :"#{name}" do
    val = instance_variable_get("@#{name}")
    val.nil? ? args[:default] : val
  end
  unless args[:read_only]
    define_method :"#{name}=" do |val|
      instance_variable_set("@#{name}", val)
    end
  end
  build_association_from(name.to_s) if name.to_s.include?("id") && ! args[:skip_association]
end

#fieldsObject



43
44
45
# File 'lib/faceted/model.rb', line 43

def fields
  @fields ||= [:id, :excludes]
end

#from(object, args = {}) ⇒ Object



47
48
49
# File 'lib/faceted/model.rb', line 47

def from(object, args={})
  materialize([object], args).first
end

#materialize(objects = [], args = {}) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/faceted/model.rb', line 51

def materialize(objects=[], args={})
  objects.compact.inject([]) do |a, object|
    interface = self.new(args)
    interface.send(:object=, object)
    interface.send(:initialize_with_object)
    a << interface
  end
end

#scopeObject



60
61
62
# File 'lib/faceted/model.rb', line 60

def scope
  parent.to_s == "Object" ? "::" : "#{parent.to_s}::"
end