setting the "view-name" of a controller - ruby-on-rails-3

I would like to centralize similar actions of some controllers and wrote a controller from which the other controllers inherites. This works fine.
# calling Configurations#index will render configurations/index.html.erb
# while 'configurations' being the internal controller_path used to look for the view
class ConfigurationsController < EditorController
end
class EditorController < ApplicationController
def index
render 'index'
end
end
But now I would like to centralise the views to the "base"-controller one's, so if an inheriting controller is called, the controller_path used should be the base-controller one's.
Is there a way, to rewrite a controllers name or controller_path?
I looked at the source of AbstractController::Base and found that (line 90)
def controller_path
#controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
end
So I just need to set #controller_path from my base-controller don't I ? This doesn't change anything:
#just does the same as above
class EditorController < ApplicationController
#controller_path = 'editor'
def index
render 'index'
end
end
So is there a way to set the controller_path manually?
great thanks in advance!

damn I found it on my own!
I just overwrote the controller_path method:
class EditorController < ApplicationController
def controller_path
'editor'
end
#...
end
this will ever use the view-folder 'editor' for any inheriting controller.

Related

Null Object Pattern for associations in Rails

Despite looking at a few answers here regarding Null Objects in rails, I can't seem to get them to work.
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
def profile
self.profile || NullProfile #I have also tried
#profile || NullProfile #but it didn't work either
end
end
class NullProfile
def display #this method exists on the real Profile class
""
end
end
class UsersController < ApplicationController
def create
User.new(params)
end
end
My problem is that on User creation, I pass in the proper nested attributes (profile_attributes) for the Profile and I end up with a NullProfile on my new User.
I am guessing that this means that my custom profile method is getting called on create and returning a NullProfile. How do I do this NullObject properly so that this only happens on read and not on the initial creation of the objects.
I was going exactly through and I wanted a clean new object if it wasn't present(if you're doing this just so object.display doesn't err maybe object.try(:display) is better) this too and this is what I found:
1: alias/alias_method_chain
def profile_with_no_nill
profile_without_no_nill || NullProfile
end
alias_method_chain :profile, :no_nill
But since alias_method_chain is being deprecated, if you're staying on the edge you would have to do the pattern by yourself manually... The answer here seems to provide the better and more elegant solution
2(Simplified/practical version from the answer):
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
module ProfileNullObject
def profile
super || NullProfile
end
end
include ProfileNullObject
end
note: The order you do this matter(explained in the linked answer)
On what you tried:
When you did
def profile
#profile || NullProfile
end
It won't behave as expected because the Association is lazily loaded(unless you told it to :include it in the search), so #profile is nil, that's why you're always getting NullProfile
def profile
self.profile || NullProfile
end
It will fail because the method is calling itself, so it's sort like a recursive method, you get SystemStackError: stack level too deep
I've found a simpler option than including a private module in the accepted answer.
You can override the reader method and fetch the associated object using the association method from ActiveRecord.
class User < ApplicationRecord
has_one :profile
def profile
association(:profile).load_target || NullProfile
end
end # class User
Instead of using alias_method_chain, use this:
def profile
self[:profile] || NullProfile.new
end
According to the Rails docs, the association methods are loaded into a module, so it's safe to override them.
So, something like...
def profile
super || NullProfile.new
end
Should work for you.

How to render rails partial from presenter layer?

Well, I'm into this situation as well now using rails 3.2.1
Following is the presenter in app/presenters/form_presenter.rb
class FormPresenter
def render_form
ActionView::Base.new.render partial: "passions/add_form"
end
end
From the view I'm calling,
...
= AddFormPresenter.new.render_form
...
But it blows with the following error:
13:14:12 ActionView::MissingTemplate - Missing partial passions/passion_concept_add_form with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=>[:erb, :builder, :slim, :coffee, :rabl]}. Searched in:
...
There is this similar question at RAILS-3.1 render method for ActionView::Base but its not helpful.
How to render this partial from the presenter layer?
Well, I just did it by grabbing the view context using a before filter. My reference was this: https://github.com/amatsuda/active_decorator/blob/master/lib/active_decorator/view_context.rb
So something like:
class FormPresenter
def render_form
FromPresenter.view_context.render partial: "passions/add_form"
end
class << self
def view_context
Thread.current[:view_context]
end
def view_context=(view_context)
Thread.current[:view_context] = view_context
end
end
module Controller
extend ActiveSupport::Concern
included do
before_filter do |controller|
FormPresenter.view_context = controller.view_context
end
end
end
end
and in application_controller.rb
class ApplicationController < ActionController::Base
...
include FormPresenter::Controller
...
end
This isn't typical of the presenter pattern. Presenters are for centralizing complicated data and logic needed to simpify the view's rendering task. Here you are rendering inside the presenter. Is this really what you intend?
Say the answer is yes. Then just creating a new ActionView::Base is asking for trouble because initializing it is non-trivial as shown here. Something strange is going on with class or some other kind of nesting. Where did the passion_concept_ prefix come from in the error message? It looks like you're not telling us all we need about your app.
You may find joy by telling the presenter explicitly where it's rendering:
class FormPresenter
def self.render_form(view)
view.render partial: "passions/add_form"
end
end
Then in the view:
= FormPresenter.render_form(self)
(Here again the explanation is not clear. What is AddFormPresenter?) I don't have a machine where I can try this at the moment, but it ought to be more debuggable than what you've got.

Helpers in controller - Rails 3

I migrated from rails 2.x to 3.x. Now when calling a controller method throws
undefined method `my_helper_method' for nil:NilClass
MyController.rb
class MyController < ApplicationController
def foo
#template.my_helper_method
end
end
MyControllerHelper.rb
class MyControllerHelper
def my_helper_method
puts "Hello"
end
end
ApplicationController
class ApplicationController < ActionController::Base
helper :all
end
How to get this working?
This is actually answered in another SO post: Rails 3: #template variable inside controllers is nil
Essentially, you can replace #template with view_context
#template is an object, in your case nil. If this object doesn't has the method (my_helper_method) in it, you cannot call it (especially not if it is nil).
Methods defined in helpers are called like regular methods. But not in controllers, they are called in views. Your helper :all just makes all helpers available to the views.
So, in your view: my_helper_method :arg1, :arg2
IF you need a method for your object (#template), you need to give your object this method.
Example:
class Template < ActiveRecord::Base
def my_helper_method
# do something on a template instance
end
end
class MyController < ApplicationController
def foo
#template = Template.first
#template.my_helper_method # which actually isn't a helper
end
end
What helpers do:
module MyHelper
def helper_method_for_template(what)
end
end
# in your view
helper_method_for_template(#template)
Mixing in a helper (be aware of having a mess in your code when mixing view helpers with views and models)
class Template < ActiveRecord::Base
include MyHelper
# Now, there is #template.helper_method_for_template(what) in here.
# This can get messy when you are making your helpers available to your
# views AND use them here. So why not just write the code in here where it belongs
# and leave helpers to the views?
end

how to access a method in a model from a controller in rails

I want to put logic in the model rather than controller.
class UsersController < ApplicationController
def somemethod
d = User.methodinmodel
end
end
class User < ActiveRecord::Base
def methodinmodel
"retuns foo"
end
end
I get an error that there is no methodinmodel for the User model.
Why?
If you want to be able to call methodinmodel on the User class in general rather than a specific user, you need to make it a class method using self:
class User < ActiveRecord::Base
def self.methodinmodel
"returns foo"
end
end
Your current method definition would only work if you called it on a user:
#user = User.create!
#user.methodinmodel # Works.
User.methodinmodel # Doesn't work.
Using the new implementation using self would allow you to call it like:
User.methodinmodel # Works.

Rails 3 Custom Class Question

I am trying to create a separate model class for image uploading, which was previously in the object's controller. I also want to make it agnostic, so I can upload images using one class from multiple objects.
In my original object's model class, I have the following now:
class Object < ActiveRecord::Base
after_save :photo_store
delegate :has_photo?, :photo, :photo_path, :store_photo, :photo_filename, :to => :photo_store
def photo_store
PhotoStore.new(self)
end
end
Then, the PhotoStore class looks like this:
class PhotoStore
attr_reader :object
def initialize(object)
#object = object
end
def photo=(file_data)
unless file_data.blank?
#file_data = file_data
self.extension = file_data.original_filename.split('.').last.downcase
end
end
PHOTO_STORE = File.join RAILS_ROOT, 'public', 'photo_store'
def photo_filename
File.join PHOTO_STORE, "#{id}.#{extension}"
end
def photo_path
"/photo_store/#{id}.#{extension}"
end
def has_photo?
File.exists? photo_filename
end
private
def store_photo
if #file_data
FileUtils.mkdir_p PHOTO_STORE
File.open(photo_filename, 'wb') do |f|
f.write(#file_data.read)
end
end
end
end
However, this throws the error below when I try and use the has_photo? method in the object's view.
undefined local variable or method `id' for #
Do I need to put some other type of relationship in place between the Object and PhotoStore?
And a separate question: What's the best way to make this agnostic? Since it uses just the ID of the object, I could just include the Object's name in the filename, but is that the best way to do it?
Thanks!
Because at File.join PHOTO_STORE, "#{id}.#{extension}" you call method PhotoStore#id, but it does not exists.
You should do that
File.join PHOTO_STORE, "#{#object.id}.#{#object.extension}"