Rails partial - local variable name from variable? - ruby-on-rails

I currently have some code to render a partial, which includes:
:locals => {:feature => y}
This works fine, but I would like to be able to use a variable in place of :feature - I have tried the following:
:locals => {type.singularize => y}
but to no avail. What is the correct syntax to replace :feature with a local variable?

Incase anyone else comes across this, I was able to resolve it using the code in the comments from apneadiving and MurifoX:
:locals => {type.singularize.to_sym => y}

Related

Generate the URL for a generic path with possible options in Rails

I'm creating a customisable nav menu for our site and have run into the following problem.
I need to generate a URL to any controller and action on the site and optionally pass it parameters. I was able to do the former by simply saying:
url_for(:controller => nav[:controller_name], :action => nav[:action_name])
which is great for sending you to {controller}/{action}. eg. news/articles
Throwing options in suddenly changes the game. Now I need to send you to something like:
{controller}/{action}/{category}/{slug}/{id}
eg. news/articles/world-domination/montana-max-vows-revenge/12345
the helper for the above would be something along the lines of:
news_article_path('world-domination', 'montana-max-vows-revenge', '12345')
and I haven't been able to replicate that in a vanilla url_for due to the arguments.
What I have done, and I don't really like is:
url_for(send("#{nav[:controller_name]}_#{nav[:action_name]}_path", *nav[:options]))
which generates the helper using send and then passes it a kwargs list. I'm sure there's a better way to do that surely?
You can do this cleanly if you are able to name the options (split here over lines for legibility):
url_for({
:controller => nav[:controller_name],
:action => nav[:action_name]
}.merge(nav[:options] || {}))
where
nav = {
:controller_name => 'news',
:action_name => 'articles',
:options => {
:category => 'world-domination',
:slug => 'montana-max-vows-revenge',
:id => '12345'
}
}

Undefined local variables in Rails 3 partials after upgrade to Ruby 1.9.3

I know there are several posts on this issue but none of the solutions I've read help here.
I've just upgraded from Ruby 1.8.7 to 1.9.3p429 and now, I get undefined local variable in my partials.
I am calling a partial (from a partial in case that's relevant) thusly:
= render :partial => 'user_name', :locals => {:user => item_user, :extra_class => "active"}
In the partial, I access these locals thusly:
- if(current_user and user.silhouette_user_id.to_i == current_user.silhouette_user_id)
= notranslate(current_user.full_name)
- else
- if !local_assigns[:extra_class].nil?
= notranslate(link_to( h(user.full_name), stream_url(:user_id => user.silhouette_user_id), :class => extra_class )) rescue "Anonymous"
- else
= notranslate(link_to( h(user.full_name), stream_url(:user_id => user.silhouette_user_id) )) rescue "Anonymous"
= notranslate(link_to "Pro", "#", :class => "badge badge-pro", :title => "#{user.part_name} is pro") if SSO.is_pro? user
I can access the locals via the local_assigns hash, so if I add these lines to the top, I have access:
user = local_assigns[:user]
extra_class = local_assigns[:extra_class]
I could live with that. However, it gets worse. user is an ActiveRecord model object. I cannot, however, access the attributes of this object with user.attribute notation. Instead I have to user user[:attribute].
I could still get by with this except that some of the attributes of user are actually methods, which I cannot access using user[:method].
I thought it might be the Rails, which was at 3.1.12 so I upgraded to 3.2.13 with no change.
Any ideas? Could it be the HAML processor? All other posts that were solved used ERB.
Try using this way for rendering partials (it's correct way for Rails 3):
= render 'user_name', user: item_user, extra_class: "active"
And access to objects using user and extra_class

Newbie - trying to save a datagrid to pdf

I'm using the gem datagrid to display some data. I would like to use ruport to output the data to pdf.
I added this button to my controller.rb=
<%= button_to "PDF", {:controller => :admin_reports, :action => :worequest_pdf }%>
I have this route=
resources :admin_reports do
post :worequest_pdf, :on => :collection
end
And this in the admin_reports_controller.rb=
def worequest_pdf
f = File.new("worequest.pdf", "w")
f.write Ruport::Data::Table(:column_names =>report.header, :data => report.rows).to_pdf
f.close
end
But, it doesn't work - any ideas?
I get:
undefined local variable or method `report' for #<AdminReportsController:0x007fc463566218>
Ruport probably is not your best option. It has not been updated in more than a year. Thats a lifetime in the ruby world. You may want to look at http://ruby-statsample.rubyforge.org/reportbuilder/ or go to https://www.ruby-toolbox.com/ to find something more up to date.
To overcome the error
undefined local variable or method `report'
Should you be using "#report" instead of "report"?

How to pass variables to render_to_string?

Trying to do the following
#message = render_to_string ( :sender => sender, :template => "template" )
But when accessing #sender in template it turns out to be nil:NilClass. Double checked if I pass the right variable and it's totally fine. Maybe there are other way to pass variables to render_to_string?
It might be the syntax you're using. Try using the :locals argument:
#m = render_to_string :template => "template", :locals => {:sender => sender}
Then you just need to access sender (without an #) as a local variable inside the template.
Here's Jason Kim's solution he wrote in a comment which worked for me:
ActionController::Base.new.render_to_string(
"user_mailer/welcome_email.html.erb", locals: { :#user => user}
)
Please mind the :#user => value bit.
In Rails 5 (atm in beta):
ApplicationController.render(
file: 'path',
assigns: { foo: 'bar' }
)
More here
Try this:
ac = ActionController::Base.new()
ac.render_to_string(:partial => 'path to your partial',:locals => {:varable => your variables})
In rails 4.0.2 this worked:
render_to_string(partial: 'path/to/partial', locals: { argument: 'value'}
I was trying to render a different format of partial in render_to_string. The thing which really worked for me was:
render_to_string(:partial => 'partial_file.html', :locals => {:variable => variable}, :format => :html)
where the name of the file was _partial_file.html.erb.

Ruby on Rails: Including multiple instance variables in partials

So... I know about the :locals => { :var1 => #rawr, :var2 => #hello } syntax for partials
but is there a way for me to pass both #rawr and #hello to the partial, so that i don't need to use var1 and var2?
You can do :locals => { :rawr => #rawr, :hello => #hello } and then the variables will be available within the partial as rawr and hello.
You know, you could just use #rawr and #hello ... and NOT pass any variables.

Resources