Helper function not returning string - ruby-on-rails-3

So I'd like to generate a random background-color based on an array:
def panel_color
a = ["#E5E0AE","#A4D349","#F1427B","#F09137","#792060"]
return a.sample
end
Simple enough. This is to be used in my disc#index.erb view, so I call it there:
...
<div class="panel" style="background-color: <% panel_color %>;">
...
Since this is a helper method for the view, I placed the function in helpers/disc_helper.rb
module DiscHelper
def panel_color
a = ["#E5E0AE","#A4D349","#F1427B","#F09137","#792060"]
return a.sample
end
end
Which, to my surprise, returns nothing to the view, but does not error, either. I'm thinking I missed something very obvious here, but I'm not quite sure what. Latest rails here.

You're just executing it, not displaying it. Use <%= ... %> instead:
<%= panel_color %>
def panel_color
["#E5E0AE","#A4D349","#F1427B","#F09137","#792060"].sample
end

Related

Why is my instance not saving for my search form?

I've got a search form that returns our products. However, if a user inputs a string that contains certain words (in this instance, 'color'), it returns far too many products. I'm trying to remove the string 'color' from the query that is searched on the backend, but maintain the original query's string as #unfiltered_query so I can reference the #unfiltered_query on the front-end template.
if query.include? "color"
#unfiltered_query = query
end
query.slice! "color"
values = query.split
binding.pry
It was not working, so I ran pry to see what was going on. In the form, I searched "Red paint color". When I call #unfiltered_query in pry, it outputs "Red paint", even though I create the method before .slice! is called?!
What am I missing?
Thank you!
p.s. the HTML template that I'm using to reference the instance is:
<div class="search-input"><h2>
<% if #unfiltered_query.present? %>
<%= #unfiltered_query.titleize %>
<% else %>
<%= query.titlelize %>
<% end %>
</h2></div>
Can you try like this :
if query.include? "color"
#unfiltered_query = query.dup
end
query.slice! "color"
values = query.split
binding.pry
This could be due to passing by reference.

How to get the current view name from layout template in Rails?

Is it possible to get the name of the currently rendered view from inside layout?
I did something like this for css namespacing:
# config/initializers/action_view.rb
ActionView::TemplateRenderer.class_eval do
def render_template_with_tracking(template, layout_name = nil, locals = {})
# with this gsub, we convert a file path /folder1/folder2/subfolder/filename.html.erb to subfolder-filename
#view.instance_variable_set(:#_rendered_template, template.inspect.gsub(/(\..*)/, '').split('/')[-2..-1].join('-'))
out = render_template_without_tracking(template, layout_name, locals)
#view.instance_variable_set(:#_rendered_template, nil)
return out
end
alias_method_chain :render_template, :tracking
end
# application.html.erb
<body class="<%= :#_rendered_template %>" >
Use <% __FILE__ %> to get the complete file path of current view, but you can only use it from within the file itself without writing some helpers
The method active_template_virtual_path method returns the template as a name in the following form "controller/action"
class ActionController::Base
attr_accessor :active_template
def active_template_virtual_path
self.active_template.virtual_path if self.active_template
end
end
class ActionView::TemplateRenderer
alias_method :_render_template_original, :render_template
def render_template(template, layout_name = nil, locals = {})
#view.controller.active_template = template if #view.controller
result = _render_template_original( template, layout_name, locals)
#view.controller.active_template = nil if #view.controller
return result
end
end
I had a similar question. I found <%= params[:controller] %> and <%= params[:action] %> to suit my need, which was to add the controller name and action name as classes on the body tag.
Just in case that helps anyone. :)
I'm currently using a modified version of Peter Ehrlich's solution. The resulting string is of the form controller_name/view_name, e.g. users/new, which means it can be passed directly to render later on, or altered to suit other uses. I've only tried this with Rails 4.2, though as far as I know it ought to work all the way back into the 3.xes.
ActionView::Base.class_eval do
attr_accessor :current_template
end
ActionView::TemplateRenderer.class_eval do
def render_template_with_current_template_accessor(template, layout_name = nil, locals = {})
#view.current_template = template.try(:virtual_path)
render_template_without_current_template_accessor(template, layout_name, locals)
end
alias_method_chain :render_template, :current_template_accessor
end
For debugging purpose, you can use gem 'current_template' from here.
This gem inspects logfile and display file name of view/partial template.
For example:
Also, you can simply add this line
<%= "#{`tail log/development.log`}".scan(/\s[a-z]+\/\S+/) %>
to your layout/application.html.erb.

Check if an attribute is validated

My problem is as follows:
I've got a form view, which needs to display success and failure icons after submit.
Before submit it just needs to show the form without the success and failure icons.
We can do this in several ways when this is the form:
<%= form_for #resource do |f| %>
<div class='<%= set_class #resource, :name %>'>
Name: <%= f.text_field :name %>
</div>
<% end %>
Check if the request is a POST:
def set_class( record, attribute )
if request.post?
if record.errors[attribute].any?
return "FAILED"
else
return "SUCCESS"
end
end
# If not submitted, we don't want a class
end
Set a flag after validation ( We can replace request.post? in above solution with record.tried_to_validate ):
class MyModel < ActiveRecord::Base
after_validation :set_tried_to_validate
attr_accessor :validated
def set_validated
#tried_to_validate = true
end
end
But I don't really like these solutions..
Isn't there an inside Rails method to check if the validation process is done?
You can first test for validity..
#form.valid?
Which will generate errors stored in 'errors' on your #form. To see if errors exist on a specific field,
#form.errors[:some_field]
On your form, you can simply do:
<% if #form.errors[:some_field].empty? %>
Valid
<% end %>
As long as some fields generate errors, the whole form will be !valid?, so you'll revert to showing the form again (:new), and you can should 'Valid' or checkmark.
I think you are looking for something like client side validations, if want the validation to show inline on the form. http://railscasts.com/episodes/263-client-side-validations
EDIT
If you want to capture the 3 stages, you can save in your db. New, Validate, Finished and just use callbacks to save each stage and set the default to new. (You will have the change the data type of the validated attribute to string)
after_validation update attribute to "validate"
after_save update attribute to "Finished"
Then you can use an if elsif else conditions to check for the value of that attribute and render the tick and cross. Obviously, this isn't pretty and you should just use valid? and the errors? helpers.

Rails and named_scope queries

I'm trying to get my head around the concept of named_scoped queries in rails.
I'm trying to filter a table to get only non featured items (:featured => false).
In my model i have added
scope :allgames, where(:featured => false)
and
scope :featured, where(featured => true)
I'm trying to list all featured and non featured items separately on my Game index page.
Is it possible to to it via a named scope.
So far i have:
<% #games.each do |item| %>
<% if item.featured %>
<%= render 'application/item_synopsis_builder', item: item %>
<% end -%>
<% end %>
And I wonder if it is possible to do something like:
<% #games.featured.each do |item| %>
<%= render 'application/item_synopsis_builder', item: item %>
<% end %>
or
<%= render partial: 'application/item_synopsis_builder', collection: #games.featured %>
When I try I get a message saying that there is no method featured.
But when I run the command Game.featured in the console I get the result list of all featured games.
Is it possible to access this list/method in the view?
Named scopes are added to the model as a class method, so trying to access the method on a collection of objects won't work. Similar functionality can be achieved with:
#games.where(:featured => true).each do
...
end
But I would recommend having two variables in your controller:
#featured_games = Games.featured
#all_games = Games.allgames
then use those in your views.
Your views are driven by the #games instance variable that is created by the controller that is rendering the views. Named scopes create a class method for subclasses of ActiveRecord::Base. So "Game.featured" returns something because defining the named scope created a method for the Game class. It did not create an instance method that objects of the Game class (such as #games) can invoke. That's why "#games.featured" gives you an error.
To do what you want to do, create two instance variable in the controller and pass them to the view, e.g.
#all_games = Game.allgames
#featured_games = Game.featured
Both variables will be available to your view, and you can construct loops to render each collection however you like.
A scope is a class method (or assimilable to, I don't know the specifics), so yes, Game.featured would work, but when you do #games.featured, you are calling featured on an array of Game instances.

Rails 3: Will_paginate's .paginate doesn't work

I'm using newes Rails 3 version with will_paginate.
#videos = user.youtube_videos.sort.paginate :page => page
I also added the ##per_page attribute to my youtube_video-model.
But it just won't paginate it. I get always all items in the collection listed.
What have I done wrong?
Yours, Joern.
Why are you calling sort here? That seems unnecessary, and probably would result in it finding all videos and calling pagination on that rather than paying any attention to any variable defined in your Video model. Instead, move the sorting logic into the Video model by using a scope or use the order method.
Here's my solution, my own answer, for all other's having trouble with will_paginate and reading this issue:
Create an ApplicationController method like this:
def paginate_collection(collection, page, per_page)
page_results = WillPaginate::Collection.create(page, per_page, collection.length) do |pager|
pager.replace(collection)
end
collection = collection[(page - 1) * per_page, per_page]
yield collection, page_results
end
Then in your Controller, where you got the collection that should be paginated:
page = setup_page(params[:page]) # see below
#messages = Message.inbox(account)
paginate_collection(#messages, page, Message.per_page) do |collection, page_results|
#messages = collection
#page_results = page_results
end
And in your View:
<% #messages.each do |message| %>
<%# iterate and show message titles or whatever %>
<% end %>
<%= will_paginate #page_results %>
To get the page variable defined, check this:
def setup_page(page)
if !page.nil?
page.to_i
else
1
end
end
So page = setup_page(params[:page]) does the trick, with that simple method.
This WORKS!