0

I've been spent a lot of time and still trying figure out how to pass a result(return) of operation to my view. As regarding documentation I created cell, operation and view folders inside concepts folder. I'm working with Search app, here is my cell/show.rb

module Search::Cell
  class Show < Trailblazer::Cell
  end
end

Here is view/show.rb

<h1> Hello! </h1>
#how to pass result here?
<a href="/search">Return back</a>

My operation/show.rb

require "trailblazer/operation"

module Search::Operation
  class Show < Trailblazer::Operation
    step    :hello_world!
    fail    :log_error

    def hello_world!(options, search_word)
      puts "Hello, Trailblazer!"
      search_word = search_word[:params]
      search_word.downcase!
      true
    end

    def log_error
      p "Some error happened!!"
      true
    end
  end
end

And search_controller.rb

class SearchController < ApplicationController
  def index
    search_word = params[:text]
    if search_word.present?
      Search::Operation::Show.(params: search_word)
      render html: cell(Search::Cell::Show).()
    else
      render html: cell(Search::Cell::Index).()
    end
  end 
end

Which variable or method should I use to pass result from operation (hello_world! method to view? I tried different things (heard some about ctx variable also tried instance variable like in common rails app) and debugging a lot with pry and didn't solve it. Please, help me!

4

1 回答 1

1

根据文档,您似乎有两种选择。

  1. 将您的操作结果作为“模型”传递,并通过单元格模板中可访问的模型变量访问它。
    class SearchController < ApplicationController
      def index
        search_word = params[:text]
        if search_word.present?
          result = Search::Operation::Show.(params: search_word)
          render html: cell(Search::Cell::Show, result)
        else
          render html: cell(Search::Cell::Index)
        end
      end 
    end

然后在您的模板中,假设您使用的是 ERB:

    <h1> Hello! </h1>
    The result is <%= model %>
    <a href="/search">Return back</a>
  1. 在上下文中传递您的操作结果,并通过单元类中定义的方法访问它。
    class SearchController < ApplicationController
      def index
        search_word = params[:text]
        if search_word.present?
          result = Search::Operation::Show.(params: search_word)
          render html: cell(Search::Cell::Show, nil, result: result)
        else
          render html: cell(Search::Cell::Index)
        end
      end 
    end

然后在你的单元格中:

    module Search::Cell
      class Show < Trailblazer::Cell
        def my_result
          #here is the logic you need to do with your result
          context[:result]
        end
      end
    end

然后在您的模板中,假设您使用的是 ERB:

    <h1> Hello! </h1>
    The result is <%= my_result %>
    <a href="/search">Return back</a>
于 2019-11-18T16:35:42.880 回答