Forum: Ruby on Rails how to add plugin to ActiveRecord

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5c312a6535a446e8e5325c5886316581?d=identicon&s=25 Mike Haggerty (ghoti143)
on 2006-06-08 18:17
I'm trying to set a date field's day to the last day of the month before
I save it.  I can do this successfully now using this code:

class Account < ActiveRecord::Base
  def before_save
    self.exp_date = last_day_of_month(self.exp_date)
  end

  # Returns a Date object set to the last day of the current month
  def last_day_of_month(date = Date.today)
      next_month_str = date.year.to_s + '-' + (date.month + 1).to_s +
'-01'
      Date.parse(next_month_str) - 1
  end
end

However, this is Ruby on Rails, and I'm trying to break all my old
programming habits like making ugly code, and this looks ugly.  Is there
a way to make this into some kind of plugin so that all I have to do is
say:


class Account < ActiveRecord::Base
  acts_as_expiration_date :exp_date
end

and it will automatically do what I want behind the scenes?

Thanks!
Mike
D0cd6b10e01bacb976b3b815a9c660bc?d=identicon&s=25 Alex Wayne (Guest)
on 2006-06-08 18:33
Mike Haggerty wrote:
> class Account < ActiveRecord::Base
>   acts_as_expiration_date :exp_date
> end

Try looking at other acts_as_* plugins and see how they work.
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (Guest)
on 2006-06-08 20:36
(Received via mailing list)
if you are onyl using this for account models, a plugin is going to be
overkill...why not just do:

class Account < ActiveRecord::Base
  before_create :set_expiry_date

  # other methods

  private
  # set the expiry date
  def set_expiry_date
    self.exp_date =  Time.now.end_of_month.to_date.to_s
  end
end

ex:

>> Time.now.end_of_month.to_date.to_s
=> "2006-06-30"

note: if you use before_save, every time you save the record, whether
it's a
new record or an update, the expiry date will be updated to reflect the
last
day of the current month...in my example, I used before_create to
indicate i
only want the expiry date set when a new record is created.

Chris
This topic is locked and can not be replied to.