rails ActiveRecord instances already have valid? method
I have an ActiveRecord Item class that gets returned by a method that has the following contract:
Contract Hash => Item
def parse_search_item_to_item(beer)
Item.new(original_name: beer.dig(:beer, :beer_name))
end
The contract sometimes fails. I think it's because valid? is called on the resulting Item. Because valid? is an ActiveRecord class and there is a validator that doesn't pass the contract fails.
i.e. Item.valid? runs the ActiveRecord validators which return false in this case.
Seems like there is a naming collision here with valid?. Any suggestions?
You can always use a Proc instead of a class as the contract when valid? is being used by the class for another purpose.
require 'contracts'
include Contracts::Core
C = Contracts
class Item
def self.valid?(_x)
false
end
end
# This won't work since Item uses valid? for another purpose
Contract C::None => Item
def foo
Item.new
end
begin
foo
rescue => e
puts e
end
# This works as desired
Contract C::None => ->(item){ item.is_a? Item }
def bar
Item.new
end
bar
Ouch. I don't have a great suggestion here, maybe I should have picked a different name...