Hi there,
my short question:
Assume I have these 2 cases in my code :
Hi there,
my short question:
Assume I have these 2 cases in my code :
I think that's overdoing the DRY thing a little bit, but if you want:
name_attr = :"#{some_condition ? 'first' : 'shared'}name"
:name => h(agent.send(name_attr))
To stay DRY, I want this to become just 1 line, by replacing "first"/"shared" by a variable that I would set at the beginning.
How would the code of this 1 new line and the initiation of the variable look like?
Well you could either use send, but to be quite honest I really wouldn't - You'll end up with something that is probably longer and certainly more complicated.
Fred
Difficult to suggest an ideal solution with such a little info, but maybe add a "first_or_shared_name" method to your Agent model, which determines which name to show, and then call that in the views instead of either firstname or sharedname:
# agent.rb def first_or_shared_name case some_method_or_variable_that_determines_which_name when :first self. firstname when :shared self.sharedname else raise "invalid value passed to my cool new method" end end
# view :name => h(agent.first_or_shared_name)
then if you want/need to, you could pass the variable to the model method from the view if it's likely to change lots:
# agent.rb def first_or_shared_name(first_or_shared) case first_or_shared ... etc end end
# view :name => h(agent.first_or_shared_name :shared)
:name => h(agent.first_or_shared_name :first)
Coming back to the point, you might just be making work for the sake of it, but I've used approaches like this when, for instance, I want to show "firstname lastname" or "title lastname" depending on whether I have the firstname or not.
That's putting business logic in the view - avoid wherever possible for sleep-filled nights...
While I agree that your solution of having a method in the model that delegates to the appropriate attribute is elegant (if the model has access to the appropriate data to make that decision), I wonder what reason we have to believe this is going on in the view?
the call to "h" gave me a clue, but if it's not a view (and he's calling view helpers in models or controllers), the principle of keeping model logic in the model is fairly sound.
that's what occurred to me as I wrote it, hence the suggestion to pass the determination in as a parameter to the method.
Like I said, with such little info from the OP, it's hard to be
conclusive. If we've given him a few different choices, one of them
might be what he needs
Thanks a lot for your quick help, guys !
Actually, all of your input is very helpful (some of it right away, some of it later)!