1

I want to display the current time (of the server) with Time.now on all sites (different controllers). Since the global displaying of headers/navigation bars and so on can be done within layout>application.html.erb I changed it to the following:

<!DOCTYPE html>
<html>
<head>
  <title>Depot</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body class='<%= controller.controller_name %>'>
<nav>
  <%= link_to 'Store', controller: 'store', action:'index' %>
  <%= link_to 'Products', controller: 'products', action: 'index' %>
  <span>Current time: <%= @time %></span>

<%= yield %>

</body>
</html>

Now I further hoped to possibly add the code to get the current time within the application_controller.rb. Here's the code I have in there

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  @time = Time.now
end

Unfortunately that's not working and I have to add the @time = Time.now - code within the controller (and method) I am using. This means I'd have to fill the code in several times and isn't that against the rails - idea?

I'd appreciate any help :)

matt
  • 78,533
  • 8
  • 163
  • 197
Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
  • Perhaps a helper is what you want that all the views can access? If that's not something you're familiar with, I can give you more info to point you in the right direction. Iceman's answer is good too (I was writing mine when he submitted his). – rdnewman Jun 09 '14 at 17:01
  • No, I am not very familiar with helpers so far. I'd highly appreciate if you could push me into the right direction. – Philipp Meissner Jun 09 '14 at 17:04
  • Like I said, I think Iceman's answer is great for this problem, but you should become familiar with helpers. I would look at this (http://stackoverflow.com/questions/18775055/helper-methods-to-be-used-in-controllers-and-views-in-rails) to give you a quick idea of the syntax. Basically, helpers are a way to make methods available to a view. Iceman's approach using a `before_action` (or `before_filter` in pre-Rails 4.x code) run code before the controller action which in this case probably is more appropriate. – rdnewman Jun 09 '14 at 17:15

1 Answers1

2

In application controller

before_action :set_time

def set_time
  @time = Time.now
end

Now you have @time available everywhere and always.

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54