Module: HasMeta::DynamicMethods::ClassMethods

Defined in:
lib/has_meta/dynamic_methods.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/has_meta/dynamic_methods.rb', line 46

def method_missing method, *args, &block
  # TODO: refactor this to not be as cluttery and dense
  attribute = self.meta_attributes.select { |x| method.match /(?<=^find_by_)#{x}(?=$|(?=_id$))/ }.pop
  if attribute
    object = find_object_from(attribute)
    if object and method =~ /_id$/
      conditions = {key: "#{attribute}_id", meta_model_type: self}.
        merge! MetaData.generate_value_hash(args.first)
        MetaData.where(conditions).map do |x|
          self.find_by_id(x.meta_model_id)
        end
    elsif !object
      conditions = {key: "#{attribute}", meta_model_type: self}.
        merge! MetaData.generate_value_hash(args.first)
      MetaData.where(conditions).map do |x|
        self.find_by_id(x.meta_model_id)
      end
    else
      super
    end
  else
    super
  end
end

Instance Method Details

#find_object_from(attribute) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/has_meta/dynamic_methods.rb', line 71

def find_object_from attribute
  begin
    attribute.to_s.classify.constantize
  rescue
    nil
  end
end

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
# File 'lib/has_meta/dynamic_methods.rb', line 37

def respond_to? method, include_private=false
  attribute = self.meta_attributes.select { |x| method.match(/(?<=^find_by_)#{x}(?=$|(?=_id$))/) }.pop
  if attribute
    find_object_from(attribute) ? !method.match(/_id$/).nil? : !method.match(/#{attribute}$/).nil?
  else
    super
  end
end