Skip to content

Commit

Permalink
Copy code from app
Browse files Browse the repository at this point in the history
This was extracted from use in an existing application. For now, I'll
copy the code as-is and go from there.
  • Loading branch information
molawson committed Jul 3, 2018
1 parent 10fa3be commit 39abf66
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion lib/boolean_timestamp.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,47 @@
require "boolean_timestamp/version"

module BooleanTimestamp
# Your code goes here...
def self.included(base)
base.extend ClassMethods
end

module ClassMethods
def boolean_timestamp(method_name)
method_name = String(method_name)
column_name = "#{method_name}_at"
fully_qualified_column_name = "#{table_name}.#{column_name}"

unless column_names.include?(column_name)
raise(
ArgumentError,
"Can't build methods from unknown column '#{fully_qualified_column_name}'",
)
end

define_singleton_method(method_name) do
where("#{fully_qualified_column_name} <= ?", Time.current)
end

define_singleton_method("not_#{method_name}") do
where(
"#{fully_qualified_column_name} IS NULL OR #{fully_qualified_column_name} > ?",
Time.current,
)
end

define_method method_name do
public_send(column_name).present? && !public_send(column_name).future?
end

alias_method "#{method_name}?", method_name

define_method "#{method_name}=" do |value|
if ActiveModel::Type::Boolean::FALSE_VALUES.include?(value)
public_send("#{column_name}=", nil)
elsif !public_send(method_name)
public_send("#{column_name}=", Time.current)
end
end
end
end
end

0 comments on commit 39abf66

Please sign in to comment.