How can I declare a global variable in Ruby on Rails? - ruby-on-rails

How can I declare a global variable in Ruby on Rails?
My sample code:
in my controller#application.rb:
def user_clicked()
#current_userid = params[:user_id]
end
in my layout#application.html.haml
I have sidebar with this link:
= link_to "John", user_clicked_path(:user_id => 1)
= link_to "Doe", user_clicked_path(:user_id => 2)
= link_to "View clicked user", view_user_path
in my views#view_user.html.haml:
%h2 #current_userid
I want to declare a global variable that can modify my controller and use it anywhere, like controller, views, and etc. The above is only a sample scenario. If I click the John or Doe link, it will send a user_id to the controller and when I click the "View clicked user" link, it will display the last clicked link. It is either John=1 or Doe=2.
Of course if I click the "View clicked user" link first, it will display nil.

In Ruby global variables are declared by prefixing the identifier with $
$foo = 'bar'
Which you rarely see used for a number of reasons. And it's not really what you are looking for.
In Ruby instance variables are declared with #:
class DemoController
def index
#some_variable = "dlroW olleH"
#some_variable = backwards
end
private
def backwards
#some_variable.reverse
end
end
Rails automatically passes the controller's instance variables to the view context.
# /app/views/demos/index.html.haml
%h1= #some_variable
Guess what it outputs and I'll give you a cookie.
In your example #global_variable is nil since controller#sample_1 is not called - the request would go through controller#sample_2.
def sample_2
#global_variable = "Hello World"
end

Related

Rails 4: What Goes in Controller and Model?

I have been reading and watching few videos on learning Rails 4. All tutorials has their own code so, in my views, easy to follow. I can't seem to learn anything or remember few things so I have decided to use my own code and see if I could follow instead of using their code.
So far I understand the Controller corresponds with the views:
# In my controller
def index
#x = "I love Ruby"
end
And in my views (index.html.erb)
<% = #x %> #=> I love Ruby
That simple thing would work for the index page. Now what if want to refer other method calls in that view's index, how to do that? In the controller:
def index
#x = "I love Ruby"
end
Still within the controller's class:
def languages_i_hate
languages = %w[
Perl
PHP
C#
C++ ]
end
And in my index.html.erb:
<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!
I got undeclared method or variable "languages_i_hate"
How do I call method names in a webpage?
What you are trying to do here is access a controller method in the view. When you do this the controller method is accessed as if it was a helper method. Normally controller methods aren't available to be used in this way, but you can tell the controller to make them available as helpers.
See http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method
BTW, when you have methods in the controller which aren't actions, ie don't correspond to a route/url, you should put them in a protected section, by convention at the bottom of the controller. This makes it clear to rails and to the reader that they're not actions.
def index
#x = "I love Ruby"
languages_i_hate
end
def languages_i_hate
#languages = %w[Perl PHP C# C++ ]
end
index.html.erb:
<%= "These are the languages I hate to bits: #{#languages_i_hate}" %>
According to rails convention you have to make use of Helpers. Other approach is by use of locals while rendering template.
def index
#x = "I love Ruby"
render :template => "index.html.erb", :locals =>{:languages_i_hate => languages_i_hate}
end
def languages_i_hate
languages = %w[
Perl
PHP
C#
C++ ]
end
And in my index.html.erb:
<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!%>

Translate controller action_name in Rails 4

I want to translate my applications' views and as I'm using partial to render headers for each view like this:
<%=t "#{controller.controller_name.capitalize} #{controller.action_name}" %>
...I got stucked on translating them. How do I translate controller.action_name in custom translation file?
I've tried to access action names like this:
parkings:
index: "Parkings index"
new: "New %{model}"
And many different variations of it, but every one failed. Could you help me?
This is a fragment of my controller:
def new
#parking = Parking.new
end
def create
#parking = Parking.new(parking_params)
if #parking.save
redirect_to #parking, notice: t(:parking_created)
else
render action: 'new'
end
end
Thanks.
You should have the translations in your locale file. Add an underscore or hyphen to separate words in the key
eg:
# config/locales/en.yml
en:
parkings_index: Parkings index
parkings_new: Parkings new page
view file
<%=t "#{controller_name}_#{action_name}" %>
First of all, when you say #{controller.controller_name} it means that you have an object called controller accessible from your view, which is not true. Even if you manage to access the controller and the name of its action I don't think it's worth the effort and time.
Instead, you can structure your translation file somehow like this:
views:
model_name (parkings): "Parkings"
action_1_name (index): "Parkings Index"
action_2_name (new): "New Parking"
...
and in your view say (for example) <%= link_to (t "views.model_name.action_name"), :action %>

How do I pass html based on ruby code / erb into a method expecting a string in Rails 3?

The following code doesn't work because I can't access the helper inside of a controller:
string << "#{has shared link_to #review.title, #review}"
But within the action (or possibly a method in the model) I still need to pass the html that would be generated from this.
I tried the template instance but doesn't work in Rails 3
Just as a basic example, say you have:
app/messages_controller.rb and
helper/messages_helper.rb
In you messages_helper.rb you may have something like what you've suggested.
#Also you should use = instead of <<
#You can only use << on a variable that has already been initialised
#a = "hello " #=> "hello"
#a << "world" #=> "hello world"
#b << "whatevs" #=> ERROR
def dummy_helper_method
#html_string = "has shared #{link_to #review.title, #review}"
#html_string
end
Then in your messages_controller.rb in any of your methods you can call your new dummy_method and you'll now get access to your #html_string instance variable
def index
dummy_helper_method
#you can now access your #html_string variable from inside this index method
end
Just as a note though, this isn't the right way to do this. You shouldn't call it in your controller unless you're trying to do something fairly specific with it which it doesn't look like you are. If you're trying to get it out into your view so that you can display it, you can actually call your helper method that you've just created in any of your messages' view files (views/messages/anything_in_here.html.erb) rather than calling it in your controller.
For example:
#views/messages/edit.html.erb
<%= dummy_helper_method %>
Anyways, hope it helps

How to generate and link to an arbitrary file?

Here's what I'm trying to do. Let's say the user is looking at the foo view for the foo action of the bar controller, and I've got a variable called #userName.
bar_controller.rb
class BarController
def foo
#userName = getUserName();
end
foo.html.erb
Hi mom!
I want to create a filed called <%= #userName %>.myExt with the information Hi, I'm <%= #userName %>! in it and put a link to it in the view. How do I do this?
i.e. final:
bar_controller.rb
def foo
#userName = getUserName();
create_myExt_file(#userName);
foo.html.erb
Hi mom! Click <%= generate link to #userName.myExt, "here" %> to view!
<#userName>.myExt
Hi, I'm <#userName>!
Ideally the #userName.myExt file doesn't have to actually be written to the hard drive, but could be created from a template or something. I don't know how to do this!
Thanks!
First, generate the file as a string, such as:
s = get_file_contents
Then, in your controller, send it to the client, along with a suggested filename:
send_data s, :filename => 'example.text'
Finally, to use an ERB template, you can just render_to_string.

Redirection in Rails

I have a small question regarding rails. I have a search controller which searches for a name in database, if found shows the details about it or else I am redirecting to the new name page. Is there anyway after redirection that the name searched for to automatically appear in the new form page?
Thanks in advance.
You can use the ActionController::Flash to pass data between actions.
def search(searchedName)
# perform search on DB
flash[:searchedName] = searchedName
redirect_to new_name
end
def new_name
end
new_name.html.erb:
<% if flash[:searchedName] %>
<%= text_field_tag flash[:searchedName] %>
<% end %>
Well, let's say you are saving this 'name' entered by user on a variable named #name.
So, on the controller that do the action of search, you did something like:
if #name
...#action if the name was found
else
session[:name] = #name
...#here is the action you did to redirect
On the declaration of the method called (you said it was 'new') :
def new
#name = session[:name] if session[:name] #I don't know exactly if the condition is this one,
#but you have to confirm that the session was instatiated
session.delete(:name) #to don't let garbage
...#continuous the action of show the new page
#and on the page you have access to a variable #name, that have the name searched before.

Resources