开发者

When to put code inside application_controller.rb

I have been creating my first site using Rails on and off for a few weeks now and constantly picking up new nuggets of info, loving it more everyday. This site has helped me imm开发者_高级运维ensely, so thank you.

I encountered a scenario when trying to set my META tags, universally using one (global) function, trying to make it DRY and all!

Is the following good or bad practice? Have I overlooked something obviously easy I could have done instead?

Now the following works a dream and seems very logical to me, but is it bad practice?

In application_controller.rb :

def make_meta_title name

  title = name

  if [params[:page]]
    title << " page " + params[:page]
  end

  title << " | My Site Name"

end

In my products_controller.rb :

def show
  ...
  @meta_title = make_meta_title(@products.name)
end

Then in my view

<title><%= @meta_title %></title>

The output

Blue widget | My Site Name

or

Blue widget page 2 | My Site Name

p.s. Please don't comment on my syntax, this is from memory as I'm on a different computer at the moment, it's along these lines though!


The application_controller.rb should contain stuff that benefits from being shared with all other controllers in your application... There are several typical use-cases for this (like some shared filters - e.g. authentication).

Now in this specific case you could use a combination of some stuff in your controller and a helper method. The controller would store the META you want to add to your pages, and the helper would generate the markup for these... Then you'd add that in your layouts/application.html.erb (or whatever templating engine you use)...


IMO putting the literal text " page " and " | My Site Name" are part of the way you present your data, and hence should be part of the view. If every page of your site follows this scheme, I would move this into your global layout page.

If, on the other hand, you sometimes create a @meta_title without using make_meta_title then what you have done seems reasonable to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜