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
64
65
66
67
68
69
70
# 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
    params[:actions] = [:retrieve] if params[:read_only] # read_only is the short form for [:retrieve]

    actions = params[:actions] if params[:actions]
    polymorphic = !!params[:polymorphic]
    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

  actions ||= [:create, :retrieve, :update, :delete]

  field_name = create_field_name(name, params, polymorphic)

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

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

    @belongs_tos ||= {}
    @belongs_tos[name] ||=
      begin
        if polymorphic
          clazz = self.class.json_type_to_class(val.type)
          id = val.id
        else
          clazz = Arrest::Source.class_loader.load(class_name)
          id = val
        end
        clazz.find(self.context, id)
      end

  end
end

#create_and_add_attribute(field_name, polymorphic, actions, 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, actions, foreign_key, class_name)
  if polymorphic
    add_attribute(PolymorphicAttribute.new(field_name.to_sym, actions))
  else
    add_attribute(BelongsToAttribute.new(field_name.to_sym, actions, :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