Ruby on Rails Thursday, June 9, 2016

> On Jun 9, 2016, at 5:41 PM, Rynn Steinbolt <lists@ruby-forum.com> wrote:
>
> Rails 3.0.2
> Ruby 1.9.3
>
> Im currently trying to have a view's instance variable respond to the
> call 'holiday?' with a boolean. i cant put it in a model's class
> definition, since i use several classes that contain dates.
> it works if I add the following definition to environment.rb:
>
> class String
> def holiday? # on timestamp as string
> if Holiday.where(date: Date.parse(self)).any?
> true
> else
> false
> end
> end
> end
>
> now i can do this in my view:
> <% if raw.timestamp.holiday? %>
>
> thats nice and all, but its really seems to be the wrong way to do this,
> not least because i have to restart the rails server to see changes to
> the method. i tried it with the following definition, but it didnt work:
>
> module ApplicationHelper
> def holiday? # on timestamp as string
> if Holiday.where(date: Date.parse(self)).any?
> true
> else
> false
> end
> end
> end
>
> (i also tried it with self.holiday?)
>
> Does anyone have a tip on how to go about this?

Adding an instance method like this is pretty much reserved for the model (or as you have noted, a monkey-patch on String). If you pass a variable into the helper, then you can do it, and the syntax isn't too much different -- it's a matter of something.holiday? vs holiday?( something.attribute ). While I agree the former is nicer, it does bind you into using the model as the source of this.

If you need to add it to more than one model, you could package it in a Concern, and then you could just include that in a number of different models, and be able to call the method there.

Walter

>
> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/00a469a36a497261dba0f5725f784a2c%40ruby-forum.com.
> For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/3DE5D46B-6247-4549-9825-7AF1601EB8E8%40wdstudio.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment