Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/time_for_a_boolean.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
require "time_for_a_boolean/railtie"

module TimeForABoolean
def time_for_a_boolean(attribute, field=:"#{attribute}_at")
def time_for_a_boolean(attribute, field=:"#{attribute}_at", scope: false)
define_method(attribute) do
!send(field).nil? && send(field) <= -> { Time.current }.()
end
Expand All @@ -25,5 +25,13 @@ def time_for_a_boolean(attribute, field=:"#{attribute}_at")
define_method(:"#{attribute}!") do
send(:"#{attribute}=", true)
end

if scope && respond_to?(:where)
singleton_class.instance_eval do
define_method(:"#{attribute}") do
where.not("#{field}": nil)
end
end
end
end
end
28 changes: 28 additions & 0 deletions spec/time_for_a_boolean_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,40 @@
end
end

describe 'scope' do
it 'does not define the scope by default' do
klass.time_for_a_boolean :attribute

expect(klass).not_to respond_to :attribute
end

it 'does not define the scope if the class does not respond to where' do
klass.time_for_a_boolean :attribute, scope: true

expect(klass).not_to respond_to :attribute
end

it 'defines the scope if the class has a where method' do
klass_with_where.time_for_a_boolean :attribute, scope: true

expect(klass_with_where).to respond_to :attribute
end
end
def klass
@klass ||= Class.new do
extend TimeForABoolean
end
end

def klass_with_where
@klass ||= Class.new do
extend TimeForABoolean

def self.where(...)
end
end
end

def object
@object ||= klass.new
end
Expand Down