Module: Videojuicer::Resource::Relationships::BelongsTo::ClassMethods

Defined in:
lib/videojuicer/resource/relationships/belongs_to.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(name, options = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/videojuicer/resource/relationships/belongs_to.rb', line 12

def belongs_to(name, options={})
  options = {
    :class=>name.to_s.capitalize,
    :foreign_key=>"#{name}_id"
  }.merge(options)
  
  define_method name do
    id = self.send(options[:foreign_key])
    klass = (options[:class].is_a?(String))? Videojuicer.const_get(options[:class]) : options[:class]
    return nil unless id
    begin
      return klass.get(id)
    rescue Videojuicer::Exceptions::NoResource
      return nil
    end
  end
  
  define_method "#{name}=" do |arg|
    self.send("#{options[:foreign_key]}=", arg.id)
  end
end