Sha256: 2b2b85eff52d49b7203d293166a2f93f92e3ee90621eb6618925c6bc971a141a

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

module DateSupercharger
  class MethodDefiner

    attr_reader :klass

    def initialize(klass)
      @klass = klass
    end

    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

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
date_supercharger-0.1.1 lib/date_supercharger/method_definer.rb