Sha256: 69c6aec9767d29f567a89b450dfc704ae18cf1ae25bf645d7f99cf6216cea9bf

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

module Microscope
  class InstanceMethod
    class DatetimeInstanceMethod < InstanceMethod
      def initialize(*args)
        super

        @now = 'Time.now'
        @cropped_field_regex = /_at$/
      end

      def apply
        return unless @field_name =~ @cropped_field_regex

        cropped_field = field.name.gsub(@cropped_field_regex, '')
        infinitive_verb = self.class.past_participle_to_infinitive(cropped_field)

        model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
          define_method "#{cropped_field}?" do
            value = send("#{field.name}")
            !value.nil? && value <= #{@now}
          end

          define_method "#{cropped_field}=" do |value|
            if Microscope::InstanceMethod.value_to_boolean(value)
              self.#{field.name} ||= #{@now}
            else
              self.#{field.name} = nil
            end
          end

          define_method "not_#{cropped_field}?" do
            !#{cropped_field}?
          end
          alias_method 'un#{cropped_field}?', 'not_#{cropped_field}?'

          define_method "#{infinitive_verb}!" do
            send("#{field.name}=", #{@now})
            save!
          end

          define_method "not_#{infinitive_verb}!" do
            send("#{field.name}=", nil)
            save!
          end
          alias_method 'un#{infinitive_verb}!', 'not_#{infinitive_verb}!'
        RUBY
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
microscope-0.6 lib/microscope/instance_method/datetime_instance_method.rb
microscope-0.5.10 lib/microscope/instance_method/datetime_instance_method.rb
microscope-0.5.9 lib/microscope/instance_method/datetime_instance_method.rb