module Yt::Associations::HasAttribute::ClassMethods

Public Instance Methods

has_attribute(attribute, options = {}, &block) click to toggle source
# File lib/yt/associations/has_attribute.rb, line 25
def has_attribute(attribute, options = {}, &block)
  define_memoized_method(attribute) do
    field = options.fetch(:from, attribute).to_s
    field = field.camelize(:lower) if options.fetch(:camelize, true)
    value = @data.fetch field, options[:default]
    value = type_cast value, options[:type] if options[:type]
    block_given? ? instance_exec(value, &block) : value
  end
end

Private Instance Methods

define_memoized_method(name, &method) click to toggle source

A wrapper around Ruby’s define_method that, in addition to adding an instance method called name, adds an instance variable called +@name+ that stores the result of name the first time is invoked, and returns it every other time. Especially useful if invoking name takes a long time.

# File lib/yt/associations/has_attribute.rb, line 42
def define_memoized_method(name, &method)
  ivar_name = "@#{name.to_s.gsub /[?!]$/, ''}"

  define_method name do
    value = instance_variable_get ivar_name
    instance_variable_set ivar_name, value || instance_eval(&method)
  end
end