Skip to content

Instantly share code, notes, and snippets.

@trevorturk
Forked from scottweisman/current.rb
Created May 7, 2012 20:27
Show Gist options
  • Save trevorturk/2630188 to your computer and use it in GitHub Desktop.
Save trevorturk/2630188 to your computer and use it in GitHub Desktop.
Using current_kase method in views
# concerns#current
module Current
extend ActiveSupport::Concern
...
def current_kase
@current_kase ||= Kase.find_by_id(params[:kase_id])
end
# To include methods in views
def self.included m
return unless m < ActionController::Base
m.helper_method :current_user, :current_kase
end
end
# sources#controller
def index
# nothing here
end
# sources#index
<h1><%= current_kase.name %></h1>
<%= link_to "Add source", new_kase_source_path %>
<% if current_kase.sources.any? %>
<% current_kase.sources.each do |source| %>
<h3><%= link_to source.name, kase_source_path(current_kase, source) %></h3>
<% end %>
<% end %>
@trevorturk
Copy link
Author

Doesn't this work?

module Current
  extend ActiveSupport::Concern

  def current_kase
    @current_kase ||= Kase.find_by_id(params[:kase_id])
  end
  helper_method :current_kase  
end

@trevorturk
Copy link
Author

For the other question, maybe this is enough for now?

def current_kase
  @current_kase ||= if params[:kase_id]
     Kase.find_by_id(params[:kase_id])
  else
     Kase.find_by_id(params[:id])
  end
end

@scottweisman
Copy link

For some reason the helper method doesn't work. Maybe I'm not loading in the concerns correctly, but the hack I found is working for now.

The conditional works perfectly, thanks!

@trevorturk
Copy link
Author

Ah, I see you need to do something like this example from Basecamp:

module Mobile
  extend ActiveSupport::Concern

  included do
    helper_method :mobile_request?, :user_agent
  end

  private
    def user_agent
      @user_agent ||= UserAgent.parse(request.user_agent)
    end

    def mobile_request?
      user_agent.mobile?
    end
end

@scottweisman
Copy link

Yep, perfect.

@trevorturk
Copy link
Author

Annoying gotcha, but I think it's worth it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment