I am trying something new and I'm stubborn, so I want to exhaust all possibilities.
I have a model called navbar with a field for links.
Inside the links field, I have stored a number of words:
profile_link community_link
The words are significant, in that, they are also the names of methods I have recorded in navbars_helper:
module NavbarsHelper
def profile_link
link_to current_user do
image_tag(current_user.image.img.mini_avatar)
current_user.name
end
end
def community_link
link_to 'Community', topics_path
end
...
end
The new thing I was trying, was to extract the words from the string and use them to call the methods in my header layout:
- if signed_in?
- #current_group.navbars do |navbar|
- if navbar.kind == "Header"
= navbar.links.to_s
navbar belongs_to group
So, what I get is the string in the header: profile_link community_link
But, what I want is a call to the methods. Is this possible? If so, can you tell me how you would do it?
I'm not very experienced working with arrays and I think it may have something to do with
I guess that it could be made working, although I am not really sure if it is worth: you are adding a lot of complexity for almost no additional benefit.
Said that, something along the lines of
- if signed_in?
- #current_group.navbars.each do |navbar|
- if navbar.kind == "Header"
- navbar.links.split(' ').each do |method|
= self.send(method)
Basically, take the string "profile_link community_link", split it using the space character and then send each method to the view (which is self in this context). Using send just executes the method as you would do normally, but gives you the benefit of deciding which method to execute at runtime :)
Related
- if clean_book_intro_component(:literary_works).present?
%h2 Other Books Related to #{#book.title}
%p.fact-text
= clean_book_intro_component(:literary_works)
Can above code written by calling clean_book_intro_component(:literary_works) only once?
Implementation of clean_book_intro_component
def clean_book_intro_component(component)
sanitize #book.intro.send(component), tags: %w(span b i p a), attributes: %w(id class style href)
end
- clean_book_intro_component(:literary_works).tap do |cbic|
- if cbic.present?
%h2 Other Books Related to #{#book.title}
%p.fact-text
= cbic
maybe I got haml wrong, but the idea is to use tap instead of explicitly saving the result of the call
Assigning variables in view is generally not recommended. However, in this case you can use an inline assignment which is generally accepted (as long as you keep the usage scoped within the context of the condition block):
if (intro = clean_book_intro_component(:literary_works)).present?
%h2 Other Books Related to #{#book.title}
%p.fact-text
= intro
Another solution is to memoize the value inside the function.
def clean_book_intro_component(component)
#component ||= {}
#component[component] ||= sanitize #book.intro.send(component), tags: %w(span b i p a), attributes: %w(id class style href)
end
However, this will cause the interpreter to retain the data as long as there is a reference to the instance. Therefore, this is recommended only in very particular cases where the execution is expensive and/or the data to be memoized is limited.
Moreover, it requires some extra complications if the helper accepts parameters. In fact, you will end up memoizing an amount of data which is linear with the possible input of the parameters.
Yes, just save the result of clean_book_intro_component(:literary_works) in a variable and then use that variable instead of invoking the function.
You could move the view into a partial and call the partial on a collection. If the collection is empty nothing is rendered. Something like:
# a related_books partial
%h2 Other Books Related to #{#book.title}
%p.fact-text
= related_books
# in the calling view
= render partial: related_books, collection: [clean_book_intro_component(:literary_works)]
See the Rails Guide about rendering collections.
How do I follow OOP standards within RoR controllers?
The setup: submitting data to a form & then manipulating it for display. This is a simplified example.
app/controllers/discounts_controller.rb
...
def show
#discount = Discount.find(params[:id])
formatted = calc_discounts(#discount)
end
...
private
calc_discounts
half_off = #discount.orig_price * .5
quarter_off = #discount.orig_price * .25
return {:half => half_off, :quarter => quarter_off}
end
...
Or is it better to place this in a library with attr_accessor and then create new instances of the library class within the controller? Or is there an even better way of accomplishing this?
The question to ask yourself is "is this logic useful for the view, model, or both?"
If the answer is that it's only useful for display purposes, I would put that logic in a view helper. If it's also beneficial to the model, put it there. Maybe something like this:
class Discount
def options
{half: (self.orig_price * .5), quarter: (self.orig_price * .25)}
end
end
Then in your controller you can just locate the record in question:
def show
#discount = Discount.find(params[:id])
end
And display it in the view:
<h1>half: <%= #discount.options[:half] %> </h1>
<h1>quarter: <%= #discount.options[:quarter] %> </h1>
Well, you can can add half_off and quarter_off as methods to your model:
class Discount < ActiveRecord::Base
def half_off
orig_price * 0.5
end
def quarter_off
orig_price * 0.25
end
end
.. and then do the following:
def show
#discount = Discount.find(params[:id])
end
Now you can call #discount.half_off and #discount.quarter_off in your view..
First off, you've got some syntax issues there. When you define methods you need to use a def keyword, and since Ruby 1.9 you can use a shortcut when defining hashes that avoids hashrockets, so it's:
def calc_discounts
half_off = #discount.orig_price * .5
quarter_off = #discount.orig_price * .25
return {half: half_off, quarter: quarter_off}
end
Also, you defined a local variable formatter inside of your controller's show method. This doesn't actually do anything but assign some values to a variable that only exists within that method. Only the controller's instance variables (variables with an #) can be passed to the view.
That being said, the best practice in RoR is to keep controllers "skinny", which means only using controllers to authenticate, authorize, load a model, assign an instance variable for you view, handle errors with any of the former, and then render the view according to the format requested.
It's another best practice not to include much logic in your views. This way, your logic can be shared with and reused by other views instead of having to be re-written for each new view you make. It also makes your views more readable, as they will read like simple lists of what is to be shown instead of making people try to decipher embedded ruby all over the place.
If the code is something that one of your other models could benefit from being able to use, put it inside your model code (or make a new plain old Ruby object if the logic is complex or not really cohesive with the existing model).
If the logic is something that is just for making a view prettier or in a better format, but won't actually be used by the models, then it should go in some type of view helper or decorator.
I've come up with an issue I can't figure out how to solve. I'm new to both Ruby and Rails, and sure there is a simple way to achieve what I'm looking for.
This is the ERB of the show view, showing two equal lines:
<p><%= #user.foo %></p>
<p><%= #user.foo %></p>
Imagine that foo is an intense computational method so I want to cache the result of the first call in order to use it in the second line without having to call foo again. The simplest option would be defining a variable and cache it:
<% foo_cache = #user.foo %>
<p><%= foo_cache %></p>
<p><%= foo_cache %></p>
But I don't want to clutter the "global" scope. A nicer way would be that foo itself could save a cache of the value it returns when it's called the first time:
def foo
return self.cached_foo if self.cached_foo #WARNING: pseudocode here!
#Not cached. Do stuff
...
self.cached_foo = computed_value
computed_value
end
My question is if it's possible to attach data to an object instance dynamically without interfering with the model behind (i.e. without making save and company functions deal with this attached data). Or maybe is there another better way to achieve what I'm looking for?
Thanks.
This is called memoization and it's a common idiom in ruby. It is usually expressed like this:
def foo
#cached_foo ||= begin
# do your heavy stuff here
end
end
#cached_foo should not interfere with ActiveRecord (like make it try to save cached_foo to the database).
What you are looking for is called memoization
def foo
#foo ||= calculate_foo
end
def calculate_foo
# heavy stuff
end
This works thanks to conditional assignment (the||=)
It's an extensive topic so I'll leave you a couple of links about it:
http://rails-bestpractices.com/posts/59-use-memoization
http://gavinmiller.io/2013/basics-of-ruby-memoization/
Plus advanced memoization in case you need to do more complicated stuff such as parameters, storing nil values
http://gavinmiller.io/2013/advanced-memoization-in-ruby/
In fact Active Support had memoizable but it was deprecated and then extracted into a gem
In case you want to use it check it out on:
https://github.com/matthewrudy/memoist
This should do it. And don't be afraid, the instance variable has no impact on the persistence layer.
def foo
#foo ||= compute_foo
end
private
def compute_foo
# ...
end
I am just learning ruby and wanting to practice writing little helper methods for rails as a good way of revising the basics.
all I would like to do is provide a counter for scoped objects.
so in my view i write this
=stats_counter_for(with_pending_state)
'pending_state' being a particular scope of the model.
def stats_counter_for(object_state)
Photo.object_state.count
end
so i want to pass this through to provide a count of all items with a pending state.
so eventually I can do
=stats_counter_for(with_active_state)
=stats_counter_for(with_inactive_state)
(the equals is from the haml view)
update error message
undefined local variable or method `with_pending_state' for #<#<Class:0x007fbce1118230>:0x007fbce1123770>
=link_to '/ Pending Approval', pending_admin_entries_path
=stats_counter_for(with_pending_state)
=link_to '/ Rejected', rejected_admin_entries_path
Where am I going wrong here? I am sure this is incredibly simple.
You can use the send method:
def stats_counter_for(state)
Photo.send("with_#{state}_state").count
end
So in your views you can use it like that:
= stats_counter_for(:active) # or as a string 'active'
= stats_counter_for(:inactive)
So basically I have a controller. something like this
def show
#user = User.find[:params[id]]
#code to show in a view
end
User has properties such as name, address, gender etc. How can I access these properties in the model? Can I overload the model accesser for name for example and replace it with my own value or concatenate something to it. Like in the show.html.erb view for this method I might want to concatenate the user's name with 'Mr.' or 'Mrs.' depending upon the gender? How is it possible?
I would hesitate to override the attributes, and instead add to the model like this:
def titled_name
"#{title} #{name}"
end
However, you can access the fields directly like this:
def name
"#{title} #{self[:name]}"
end
You can create virtual attributes within your model to represent these structures.
There is a railscast on this very subject but in summary you can do something like this in your model
def full_name
[first_name, last_name].join(' ')
end
def full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end
If you wish to explicitly change the value of an attribute when reading or writing then you can use the read_attribute or write_attribute methods. (Although I believe that these may be deprecated).
These work by replacing the accessor method of the attribute with your own. As an example, a branch identifier field can be entered as either xxxxxx or xx-xx-xx. So you can change your branch_identifier= method to remove the hyphens when the data is stored in the database. This can be achieved like so
def branch_identifier=(value)
write_attribute(:branch_identifier, value.gsub(/-/, '')) unless value.blank?
end
If you are accessing data stored directly in the database you can do this in you view:
<%= #user.firstname %>
<%= #user.gender %>
etc.
If you need to build custom representations of the data, then you will either need to create helpers, or extend the model (as above).
I tend to use helper methods added to the model for things like that:
def formatted_name
"#{title} #{first_name} #{last_name}"
end
(Edit previous post. Looked back at my code and realized helpers are supposed to be for presentation-related (mark-up) stuff only.)
(Edit again to remove left-over parameter... Geez, not enough coffee this morning.)
(Edit again to replace $ with #... Perhaps I should just remove this one huh?)
You can easily overload the attributes as you suggest.
i.e. if name is a field in the users database table, you can do:
def name
"#{title} #{read_attribute[:name]}"
end
The read_attribute function will return the database column value for the field.
Caveat: I am not sure this is a good idea. If you want a method that displays model data in a modified way, I would be tempted not to overload the default methods, and call them something different - this will avoid a certain level of obfuscation.
Documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html (under 'Overwriting default accessors')
in http://api.rubyonrails.org/classes/ActionController/Base.html
search for
Overwriting default accessors