Class: DateSupercharger::MethodDefiner

Inherits:
Object
  • Object
show all
Defined in:
lib/date_supercharger/method_definer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ MethodDefiner

Returns a new instance of MethodDefiner.



6
7
8
# File 'lib/date_supercharger/method_definer.rb', line 6

def initialize(klass)
  @klass = klass
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



4
5
6
# File 'lib/date_supercharger/method_definer.rb', line 4

def klass
  @klass
end

Instance Method Details

#define(opts) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/date_supercharger/method_definer.rb', line 10

def define(opts)
  attribute = opts[:attribute]
  suffix = opts[:suffix]

  new_method = "#{attribute}_#{suffix}"
  case suffix
  when :after,:before,:before_or_at,:after_or_at
    operators = { after: ">", before: "<", before_or_at: "<=", after_or_at: ">=" }
    klass.singleton_class.class_eval do
      define_method(new_method) do |date|
        where("#{attribute} #{operators[suffix]} ?", date)
      end
    end
  when :between,:between_inclusive
    methods = {between: ["after_or_at","before"],between_inclusive:["after_or_at","before_or_at"]}
    klass.singleton_class.class_eval do
      define_method(new_method) do |from,to|
        from_method = methods[suffix].first
        to_method = methods[suffix].second
        send("#{attribute}_#{from_method}",from).send("#{attribute}_#{to_method}",to)
      end
    end
  end
end