Module: ContentfulModel::Associations::HasOne::ClassMethods

Defined in:
lib/contentful_model/associations/has_one.rb

Instance Method Summary collapse

Instance Method Details

#has_one(association_name, options = {}) ⇒ Object

has_one defines a method on the parent which wraps around the superclass’s implementation. In most cases this will end up at ContentfulModel::Base#method_missing and look at the fields on a content object. We wrap around it like this so we can specify a class_name option to call a different method from the association name. class Foo

has_one :special_bar, class_name: "Bar"

end

Parameters:

  • association_name (Symbol)

    the name of the association. In this case Foo.special_bar.

  • options (Hash) (defaults to: {})

    a hash, the only key of which is important is class_name.



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

def has_one(association_name, options = {})
  default_options = {
    class_name: association_name.to_s.classify
  }
  options = default_options.merge(options)
  # Define a method which matches the association name
  define_method association_name do
    begin
      # Start by calling the association name as a method on the superclass. This will probably end up at ContentfulModel::Base#method_missing
      super()
    rescue ContentfulModel::AttributeNotFoundError
      # If method_missing returns an error, the field doesn't exist. If a class is specified, try that.
      if options[:class_name].underscore.to_sym != association_name
        self.send(options[:class_name].underscore.to_sym)
      else
        #otherwise give up and return nil
        nil
      end
    end
  end
end