I have a variable value
that is initialized when I create a new object. However, this variable is not a column of my table. I just want to use it inside my model and have it available for some methods inside my class:
class MyClass < ActiveRecord::Base
def initialize (value)
@value = value
end
end
So, when a create a new object @value
will keep the some text
temporarily, for example:
test = MyClass.new("some text")
There is a way to validates the variable value
to accept only text?
class MyClass < ActiveRecord::Base
validates_format_of :value => /^\w+$/ # it doesn't work
def initialize (value)
@value = value
end
end
EDIT
I have tried all the answer, but my Rspec is still passing:
My new class:
class MyClass < ActiveRecord::Base
validate :check_value
def check_value
errors.add(:base,"value is wrong") and return false if !@value || !@value.match(/^\w+$/)
end
def initialize (value)
@value = value
end
def mymethod
@value
end
end
My Rspec (I was expecting it to fail, but it is still passing):
describe MyClass do
it 'checking the value' do
@test = MyClass.new('1111').mymethod
@test.should == '1111'
end
end
I would like to raise an validation error before assigning 1111
to the @value
.