Where to add code to add a method to String class?
Closed this issue · 5 comments
Where would you put code to add a method to the String class?
I'm sorry, I don't understand what you're trying to do.
Maybe if you give me an example I might be able to give you a better answer.
I need to test whether a string contains a valid date so I can convert it properly in a 'before_save'. The way I thought I could do that is to extend the String class with an is_date? method.
class String
def is_date?
begin
return true if Date.parse(self)
rescue
#do nothing
end
return false
end
end
Then I can test the string from the SQL db like so;
"some string that may contain a date".is_date?
I know how to make it work in a Rails console by requiring the file. I'm not that familiar with Ruby command lines apps and cant figure out where to put the code. I can share more if that would help.
I think inside the translation file (in the table), you might be able to do def is_date?
. and call it inside the before_save block. I"m not too sure how to include it otherwise. If it doesn't work including it into the translation file, then let me know and I'll look into it a bit deeper.
Thanks Anlek. For the benefit of anyone else reading this, here is what worked in the translation file;
table "accounts" do
column "account_no", :key, :as => :string
column "my_date", :string
before_save do |row|
row.my_date = is_date(row.my_date) ? Date.strptime(row.my_date,"%Y-%m-%d %H:%M:%S").to_time : ""
end
def is_date(date_str)
begin
return true if Date.parse(date_str)
rescue
#do nothing
end
return false
end
end
I'm so glad you got it working and thank you very much for sharing it with everyone else!