andypike / rectify

Build maintainable Rails apps
MIT License
596 stars 48 forks source link

undefined method `helper_method' when including Rectify::ControllerHelpers #43

Closed zarapustra closed 7 years ago

zarapustra commented 7 years ago

Hello, i am trying to implement Rectify gem in my new rails app. So when i include Rectify::ControllerHelpers into Command, i got error

NoMethodError:
       undefined method `helper_method' for Post::Command::Create:Class

Without this line, Command works great except those 'expose' and 'presenter' methods.

Gemfile

gem 'rails', '~> 5.1.4'
gem 'puma', '~> 3.7'
gem 'bcrypt', '~> 3.1.7'

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem 'pg'
gem 'jwt'
gem 'multi_json'
gem 'rectify' #  using rectify (0.10.0)

group :development do
  gem 'pry-rails'
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'

  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'capybara', '~> 2.13'
  gem 'rspec-rails'
  gem 'selenium-webdriver'
  gem 'database_cleaner', '~>1.6.1'
  gem 'faker'
  gem 'shoulda-matchers', '~> 3.0'
  gem 'factory_girl_rails'
end

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'parallel_tests'
end

Command

class Post::Command::Create < Rectify::Command
  include Rectify::ControllerHelpers

  def initialize(params)
    @params = params
  end

  def call
    return broadcast(:error, form.errors) if form.invalid?
    broadcast(:ok, presenter)
  end

  private

  def presenter
    Post::PostPresenter.new(post: model)
  end

  def model
    Post.create(form.attributes)
  end

  def form
    @_form ||= Post::PostForm.from_params(@params)
  end
end
andypike commented 7 years ago

Hi @zarapustra

Thanks for the question. Rectify::ControllerHelpers is only supposed to be included in your controllers to provide them with some nicer ways to deal with presenters. There's a section in the readme here: https://github.com/andypike/rectify#presenters

Normally a Command is just for encapsulating the business logic and doesn't normally contain the presenter or form (but if you prefer that way, it can be done).

Looking at your example, try removing include Rectify::ControllerHelpers from the Command and adding it to your controller. Then inside the action where you call the Command you should be able to do something like:

class PostsController < ApplicationController
  include Rectify::ControllerHelpers

  def create
    Post::Command::Create.call(params) do
      on(:ok) { |presenter| present(presenter) }
      on(:error) { |errors| render(:new) }
    end
  end
end

I think that will work 😄

Andy