← Back to Upcase

Accessing Rails helpers/variables


(Lenart Rudel) #1

I’m using Shortcodes gem for replacing string tokens with custom code. The gem supports HAML and ERB templates which are loaded from a directory (e.g. app/views/shortcodes). I don’t know how to access any of the Rails helpers or the controller variables etc. from the templates.

I want user to be able to use [gallery] tag without explicitly providing the id since I can get it through model relations. The problem is that I don’t know how to get to the @article variable which is set by the controller. I’ve used pry and have played around listing the environment variables etc. but haven’t found anything useful. Is there a way to get to rails’ controller “by hand” (e.g. Rails.application.xxx?

Could someone give me a direction on how to do it?

Here’s some code from the actual app to get a picture

#
# app/views/shortcodes/gallery.html.haml

# This is the code I wish I'd have:
- @article.gallery.images.each do |img|
  = render img
  ...

# This is the code I'm stuck with now:
- gallery = Gallery.where(id: @attributes[:id])
- gallery.images.each do |image|
  %div{id: "image-#{image.id}", class: 'image col-md-4'}
    %img{src: image.photo(:medium), alt: image.title}
    %h4= image.title
    = image.description

#
# app/controllers/articles_controller.rb
def show
  @article = ArticlePresenter.find params[:id]
end

#
# app/presenters/article_presenter.rb
class ArticlePresenter
  attr_reader :article
  ...
  def body
    @body ||= Shortcode.process article.content
  end
end