As would be appropriate to make an exception in the model? - ruby-on-rails

I have a method parse_date_if_not_null which parses the date and time. But it so happens that the user entered an incorrect date format and time, then you need to show the error. I implemented it this way.
But I think, catch here only wrong format exception.
As would be appropriate to make an exception?
def parse_date_if_not_null
unless self.date_string.blank?
begin
self.ends_at = DateTime.strptime self.date_string, '%m/%d/%Y %H:%M'
rescue
errors.add(:date_string, _("Wrong date format, example: MM/DD/YYYY HH/MM"))
end
end
end

Yes it will be appropriate to make an exception in the model, you can do something like this..
class ...
validate: parse_data_if_not_null
def parse_data_if_not_null
unless self.date_string.blank?
erros.add(:date_string, 'Wrong date format, example: ...') if ((self.ends_at = DateTime.strptime self.date_string, '%m/%d/%Y %H:%M') rescue ArgumentError) == ArgumentError)
end
end

Related

Best way to recover from a failed model save in rails

I have some code to get some tweets from the twitter API:
initial_tweets = get_tweets_in_time_range self.name, (Time.now-1.weeks), Time.now
initial_tweets.each do |tweet|
new_tweet = Tweet.new
new_tweet.favorite_count = tweet.favorite_count
new_tweet.filter_level = tweet.filter_level
new_tweet.retweet_count = tweet.retweet_count
new_tweet.text = tweet.text
new_tweet.tweeted_at = tweet.created_at
new_tweet.created_at = DateTime.strptime tweet.created_at.to_s, '%Y-%m-%d %H:%M:%S %z'
new_tweet.save
# What happens on a failed save
end
Whats the correct fallback if that save fails? As pointed out where the comment is. Thanks for any help.
save only return true or false, you can use save!, it will raise an exception if the record is invalid. if exception raised, you can catch it.
begin
....
new_tweet.save!
rescue exception => e
puts e.inspect
#you can continue the loop or exit
end
as #Stefan said, you can wrap you code in a transaction, if one record save failed, all saved record will rollback. I don't advise you to do this unless you really want every record saved success.
Tweet.transaction do
initial_tweets = get_tweets_in_time_range self.name, (Time.now-1.weeks), Time.now
initial_tweets.each do |tweet|
new_tweet = Tweet.new
.....
new_tweet.created_at = DateTime.strptime tweet.created_at.to_s, '%Y-%m-%d %H:%M:%S %z'
new_tweet.save! # you have to add '!', once save failed, it will trigger rolls back.
end
end

Providing defaults if params aren't present

I'm trying to create a function that will return defaults if date parameters are not set.
If params[:start_time] not present? return DateTime.now and if params[:end_time] not present? return 1.week.from_now
I'd like to keep these two checks in one function but I can't get it working. If there a better way?
# Main search function
def self.search params, location
self
.join.not_booked
.close_to(Venue.close_to(location))
.activity(Activity.get_ids params[:activity])
.start_date(valid_date params[:start_time])
.endg_date(valid_date params[:end_time])
.ordered
end
# Check if date is nil
def self.valid_date date
if date
date.to_datetime
elsif date == params[:start_time]
DateTime.now
elsif date == params[:end_time]
1.week.from_now
end
end
Asked another way:
What's the best way to combine these two functions?
# Check if date is nil
def self.check_start date
date.present? ? date.to_datetime : DateTime.now
end
def self.check_end date
date.present? ? date.to_datetime : 1.week.from_now
end
If it's not a hard requirement to combine those two methods, you can simply and easily have these two different methods for checking the validity of start_time and end_time:
def self.validate_start_date start_date
start_date.present? ? start_date.to_datetime : DateTime.now
end
def self.validate_end_date end_date
end_date.present? ? end_date.to_datetime : 1.week.from_now
end
Then, in your main search function use them accordingly (start_date(validate_start_date params[:start_time]) and end_date(validate_end_date params[:end_time])):
# Main search function
def self.search params, location
self
.join.not_booked
.close_to(Venue.close_to(location))
.activity(Activity.get_ids params[:activity])
.start_date(validate_start_date params[:start_time])
.end_date(validate_end_date params[:end_time])
.ordered
end
Perhaps I'm misunderstanding but why not:
def self.check param
result = 1.week.from_now
if param[:end_time].present?
result = param[:end_time].to_datetime
end
return result
end
Your second "end_time" check will always overwrite any possible result from your "start_time" if we put it into one function.

Ruby rescue multiple specific errors

In Rails i am trying to validate dates that are being imported through an excel document. it wont go through ActiveRecord so i cant use the Timeliness gem that i have in the system that i use to verify other dates.
So i wrote my own gem that verifies the format of a date, but there are some dates that get through that are not valid like 31/04/2013, if the date is in an incorrect format then it will raise a RuntimeError which i rescue and supply a error message. but in ruby:
Date.new(2013,4,31)
ยป ArgumentError: invalid date
So i would like to rescue either of them. i am just afraid that some ArgumentError will appear and it wont be this exact one. so i would like it to rescue only ArgumentError: invalid date, is this possible?
This is the excel date checker i wrote
def as_date
return nil if self.blank?
begin
date = DateDojo::DateSensei.date_format_validation(self)
if date.class == Date
return date
else
return false
end
rescue RuntimeError
:invalid_date_format_to_make_validations_cry_and_die_sad_face
rescue ArgumentError
:dates_that_wouldnt_exist_even_in_the_correct_format
end
end
You can target a specific error message like so:
begin
...
rescue ArgumentError => e
if e.message =~ /invalid date/
# Do something
else
puts e.message
end
end

Rails: controller won't update model correctly

I apologize in advance, this is going to be a long question.
Short version:
I have a Meeting model that has a date, start_time, and end_time. These are time objects, which of course are a pain for users to input, so I'm using virtual attributes to accept strings which are parsed by Chronic before save.
I have a plain vanilla rails controller that receives these virtual attributes from the form and passes them along to the model. Here is the controller:
def create
#meeting = #member.meetings.build(params[:meeting])
if #meeting.save
redirect_to member_meetings_path(#member), :notice => "Meeting Added"
else
render :new
end
end
def update
#meeting = #member.meetings.find(params[:id])
if #meeting.update_attributes(params[:meeting])
redirect_to member_meetings_path(#member), :notice => "Meeting Updated"
else
render :new
end
end
I've verified that the controller receives the correct parameters from the form, for instance params[:meeting][:date_string] is set as expected.
Problems:
On create, the date gets set correctly, but the times are assigned to the year 2000, set in UTC, and won't display in local time on the front end.
On update, the date won't update. The times update but stay in UTC for 2000-01-01.
Longer Version
What makes this super bizarre to me is I have decent test coverage indicating all of this works at the model layer.
Here is the model:
# DEPENDENCIES
require 'chronic'
class Meeting < ActiveRecord::Base
# MASS ASSIGNMENT PROTECTION
attr_accessible :name, :location, :description, :contact_id, :member_id, :time_zone,
:date, :start_time, :end_time, :date_string, :start_time_string, :end_time_string
# RELATIONSHIPS
belongs_to :member
belongs_to :contact
# CALLBACKS
before_save :parse_time
# Time IO Formatting
attr_writer :date_string, :start_time_string, :end_time_string
# Display time as string, year optional
def date_string(year=true)
if date
str = "%B %e"
str += ", %Y" if year
date.strftime(str).gsub(' ',' ')
else
""
end
end
# Display time as string, AM/PM optional
def start_time_string(meridian=true)
if start_time
str = "%l:%M"
str += " %p" if meridian
start_time.strftime(str).lstrip
else
""
end
end
# Display time as string, AM/PM optional
def end_time_string(meridian=true)
if end_time
str = "%l:%M"
str += " %p" if meridian
end_time.strftime(str).lstrip
else
""
end
end
# Display Date and Time for Front-End
def time
date.year == Date.today.year ? y = false : y = true
start_time.meridian != end_time.meridian ? m = true : m = false
[date_string(y),'; ',start_time_string(m),' - ',end_time_string].join
end
private
# Time Input Processing, called in `before_save`
def parse_time
set_time_zone
self.date ||= #date_string ? Chronic.parse(#date_string).to_date : Date.today
self.start_time = Chronic.parse #start_time_string, :now => self.date
self.end_time = Chronic.parse #end_time_string, :now => self.date
end
def set_time_zone
if time_zone
Time.zone = time_zone
elsif member && member.time_zone
Time.zone = member.time_zone
end
Chronic.time_class = Time.zone
end
end
Here is the spec. Note that to test the parse_time callback in isolation I'm calling #meeting.send(:parse_time) in these tests whenever I'm not actually creating or updating a record.
require "minitest_helper"
describe Meeting do
before do
#meeting = Meeting.new
end
describe "accepting dates in natural language" do
it "should recognize months and days" do
#meeting.date_string = 'December 17'
#meeting.send(:parse_time)
#meeting.date.must_equal Date.new(Time.now.year,12,17)
end
it "should assume a start time is today" do
#meeting.start_time_string = '1pm'
#meeting.send(:parse_time)
#meeting.start_time.must_equal Time.zone.local(Date.today.year,Date.today.month,Date.today.day, 13,0,0)
end
it "should assume an end time is today" do
#meeting.end_time_string = '3:30'
#meeting.send(:parse_time)
#meeting.end_time.must_equal Time.zone.local(Date.today.year,Date.today.month,Date.today.day, 15,30,0)
end
it "should set start time to the given date" do
#meeting.date = Date.new(Time.now.year,12,1)
#meeting.start_time_string = '4:30 pm'
#meeting.send(:parse_time)
#meeting.start_time.must_equal Time.zone.local(Time.now.year,12,1,16,30)
end
it "should set end time to the given date" do
#meeting.date = Date.new(Time.now.year,12,1)
#meeting.end_time_string = '6pm'
#meeting.send(:parse_time)
#meeting.end_time.must_equal Time.zone.local(Time.now.year,12,1,18,0)
end
end
describe "displaying time" do
before do
#meeting.date = Date.new(Date.today.year,12,1)
#meeting.start_time = Time.new(Date.today.year,12,1,16,30)
#meeting.end_time = Time.new(Date.today.year,12,1,18,0)
end
it "should print a friendly time" do
#meeting.time.must_equal "December 1; 4:30 - 6:00 PM"
end
end
describe "displaying if nil" do
it "should handle nil date" do
#meeting.date_string.must_equal ""
end
it "should handle nil start_time" do
#meeting.start_time_string.must_equal ""
end
it "should handle nil end_time" do
#meeting.end_time_string.must_equal ""
end
end
describe "time zones" do
before do
#meeting.assign_attributes(
time_zone: 'Central Time (US & Canada)',
date_string: "December 1, #{Time.now.year}",
start_time_string: "4:30 PM",
end_time_string: "6:00 PM"
)
#meeting.save
end
it "should set meeting start times in the given time zone" do
Time.zone = 'Central Time (US & Canada)'
#meeting.start_time.must_equal Time.zone.local(Time.now.year,12,1,16,30)
end
it "should set the correct UTC offset" do
#meeting.start_time.utc_offset.must_equal -(6*60*60)
end
after do
#meeting.destroy
end
end
describe "updating" do
before do
#m = Meeting.create(
time_zone: 'Central Time (US & Canada)',
date_string: "December 1, #{Time.now.year}",
start_time_string: "4:30 PM",
end_time_string: "6:00 PM"
)
#m.update_attributes start_time_string: '2pm', end_time_string: '3pm'
Time.zone = 'Central Time (US & Canada)'
end
it "should update start time via mass assignment" do
#m.start_time.must_equal Time.zone.local(Time.now.year,12,1,14,00)
end
it "should update end time via mass assignment" do
#m.end_time.must_equal Time.zone.local(Time.now.year,12,1,15,00)
end
after do
#m.destroy
end
end
end
I have even specifically mixed in creating and updating records via mass assignment in later test methods to ensure that those work as expected. All those tests pass.
I appreciate any insight into the following:
Why doesn't the date update in the controller#update action?
Why aren't times getting the year from the date that is set? This works in the model and in specs, but not when submitted via form through the controller.
Why don't times get set to the time zone that is passed in from the form? Again, these specs pass, what is wrong on the controller?
Why won't times display in their time zone on the front end?
Thanks for the help, I feel like I must be losing the forest for the trees on this one as I've been going at it for hours.
Update:
Thanks to the help of AJcodez, I saw some of the issues:
Was assigning date wrong, thanks AJ! Now using:
if #date_string.present?
self.date = Chronic.parse(#date_string).to_date
elsif self.date.nil?
self.date = Date.today
end
I was using Chronic correctly, my mistake was at the database layer! I set the fields in the database to time instead of datetime, which ruins everything. Lesson to anyone reading this: never ever use time as a database field (unless you understand exactly what it does and why you're using it instead of datetime).
Same problem as above, changing the fields to datetime fixed the problem.
The problem here has to do with accessing time in the model vs. the view. If I move these time formatting methods into a helper so they're called in the current request scope they will work correctly.
Thanks AJ! Your suggestions got me past my blind spot.
Well here goes..
1 . Why doesn't the date update in the controller#update action?
I see two potential issues. Looks like you're not parsing the dates again. Try this:
def update
#meeting = #member.meetings.find(params[:id])
#meeting.assign_attributes params[:meeting]
#meeting.send :parse_time
if #meeting.save
...
assign_attributes sets but doesnt save new values: http://apidock.com/rails/ActiveRecord/AttributeAssignment/assign_attributes
Also, in your parse_time method, you use this assignment: self.date ||= which will always set self.date back to itself if it is assigned. In other words you can't update the date unless its falsey.
2 . Why aren't times getting the year from the date that is set? This works in the model and in specs, but not when submitted via form through the controller.
No idea, looks like you are using Chronic#parse correctly.
3 . Why don't times get set to the time zone that is passed in from the form? Again, these specs pass, what is wrong on the controller?
Try debugging time_zone and make sure it is returning whats in params[:meeting][:time_zone]. Again it looks correct by Chronic.
Side note: if you pass an invalid string to Time#zone= it will blow up with an error. For instance Time.zone = 'utc' is all bad.
4 . Why won't times display in their time zone on the front end?
See Time#in_time_zone http://api.rubyonrails.org/classes/Time.html#method-i-in_time_zone and just explicitly name your time zone every time.
Not sure if you're already doing this, but try to explicitly save Times in UTC on the database, and then display them in local time.

Format date time in find operation in Rails 3

I'm looking for a way to format date time in find(:all) so that when I render my results in JSON, the date time will look like
"March 20, 2011"
instead of
"2011-03-20T04:57:50Z"
Does anyone have any suggestion? Thanks.
OK, so you want to render the results in JSON formatted nicely. Instead of changing the format of the date on the way in, change it on the way out.
class Post
def formatted_created_at
created_at.strftime("%b %d, %Y")
end
def as_json(args={})
super(:methods=>:formatted_created_at, :except=>:date)
end
end
I would have used Date.parse(datestring) on the client to generate some usable content.
Time.now().strftime("%b %d, %Y)
Off the top of my head, you could do something like:
#posts = Post.all
#posts.all.each do |x|
x.date = x.date.strftime("%b %d, %Y")
end
#posts.to_json
That works (checked in Rails 3.1), put it into config/initializer/times_format.js. First two lines fix default time format (e.g. AR created_at). Third part is monkey patch for JSON.
Date::DATE_FORMATS[:default] = "%Y-%m-%d"
Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S"
class ActiveSupport::TimeWithZone
def as_json(options={})
strftime('%Y-%m-%d %H:%M:%S')
end
end
Look you use jbuilder? and for example index.json.jbuilder
json.array!(#textstrings) do |textstring|
json.extract! textstring, :id, :text
json.created_at textstring.created_at.to_formatted_s(:short)
json.url textstring_url(textstring, format: :json)
end
in this example I am use method .to_formatted_s
json.created_at textstring.created_at.to_formatted_s(:short
and i've got
[{"id":1,"text":"liveasda","created_at":"17 Nov 12:48","url":"http://localhost:5555/textstrings/1.json"},{"id":2,"text":"123","created_at":"17 Nov 14:26","url":"http://localhost:5555/textstrings/2.json"},

Resources