Module: Lazy::Attribute::ClassMethods

Defined in:
lib/lazy/attribute/lazy_attribute.rb

Instance Method Summary collapse

Instance Method Details

#lazy_attribute(attribute, options = {}) ⇒ none

Including the lazy_attribute gem to the model

Parameters:

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

Options Hash (options):

  • :key (Symbol) — default: :default

    if the key parameter is not set, it will take the default as the key

  • :create_if_not_found (Boolean) — default: false

    if the parameter is set as true, will create the record if the record is not available

  • :raise_error (Boolean) — default: false

    will raise exceptions ActiveRecord::RecordNotFoundException if the value set as true and the record not present
    ActiveRecord::RecordInvalid: Validation failed exception if any validation error thrown at the time of creation missing record

Returns:

  • (none)


17
18
19
20
21
22
23
24
25
26
# File 'lib/lazy/attribute/lazy_attribute.rb', line 17

def lazy_attribute(attribute, options = {})
  default_options = {raise_error: false, key: '[]', create_if_not_found: false}
  options.reverse_merge!(default_options)

  singleton_class.instance_eval do
    define_method(options[:key]) do |identifier|
      send(dynamic_find_method(options), {attribute.to_sym => identifier})
    end
  end
end