Module: Arrest::BelongsTo::BelongsToMethods

Defined in:
lib/arrest/attributes/belongs_to.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(*args) ⇒ Object



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
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/arrest/attributes/belongs_to.rb', line 28

def belongs_to(*args)
  arg = args[0]
  name = arg.to_s.downcase
  class_name = StringUtils.classify(name)
  foreign_key = "#{StringUtils.underscore(ClassUtils.simple_name(self))}_id"
  params = args[1] unless args.length < 2

  if params
    read_only =  params[:read_only] == true
    polymorphic = params[:polymorphic] unless params[:polymorphic] == nil
    class_name = params[:class_name].to_s unless params[:class_name] == nil
    foreign_key = params[:foreign_key].to_s unless params[:foreign_key] == nil
  end

  field_name = create_field_name(name, params, polymorphic)

  create_and_add_attribute(field_name, polymorphic, read_only, foreign_key, class_name)

  send :define_method, name do
    val = self.send(field_name)
    if val == nil || val == ""
      return nil
    end

    begin
      if polymorphic
        Arrest::Source.mod.const_get(polymorphic[val.type.to_sym]).find(self.context, val.id)
      else
        Arrest::Source.mod.const_get(class_name).find(self.context, val)
      end
    rescue Errors::DocumentNotFoundError => e
      raise Errors::DocumentNotFoundError, "Couldnt find a #{class_name} with id #{val}"
    end

  end
end

#create_and_add_attribute(field_name, polymorphic, read_only, foreign_key, class_name) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/arrest/attributes/belongs_to.rb', line 20

def create_and_add_attribute(field_name, polymorphic, read_only, foreign_key, class_name)
  if polymorphic
    add_attribute(PolymorphicAttribute.new(field_name.to_sym, read_only))
  else
    add_attribute(BelongsToAttribute.new(field_name.to_sym, read_only, String, foreign_key, class_name))
  end
end

#create_field_name(name, params, polymorphic) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/arrest/attributes/belongs_to.rb', line 10

def create_field_name(name, params, polymorphic)
  if (params && params[:field_name])
    params[:field_name]
  elsif polymorphic
    "#{name}_ref"
  else
    "#{name}_id"
  end
end