arve
arve

Reputation: 801

view to call a class method in ruby on rails?

I have set up a class in my lib folder, call it a service.rb file which manage messaging with a 3rd party api( sample below). this class serves as interface between , my code & functionality provided by the 3rd party api.

I want to be able to show messages sent/eceived in a view/partial view , that i can stick it in any other view.

can I call this code from any view? or do i need to create a view/partial view specifially for this class. also i don't have a controller or a model class for this , which is the convention in ruby on rails. what is the best way to do this?

class Messaging
   include ThirdyPartyLibrary

   def send
   end

   def receive
   end
end

Upvotes: 0

Views: 568

Answers (1)

max
max

Reputation: 102250

This is just conceptually wrong.

A view should not call a service at all - especially not if it involves a third party API. In Rails your views just take data from the controller and use that to render HTML. Its the controllers job to call a service and pass the data to the view.

Why? Because views are a mixture of HTML and Ruby and should be kept as simple as possible. And doing API or DB calls in your views can lead to serious performance issues as its hard to get an overview of where and when they are called.

Use a concern if you want to share the code for fetching the messages in the controller:

# app/controllers/concerns/messaging/controller_integration.rb
module Messaging
  module ControllerIntegration
    extend ActiveSupport::Concern

    included do
      before_action :fetch_messages
    end

    def fetch_messages
      @messages = MessageService.call #
    end
  end
end

class FoosController < ApplicationController
  include Messaging::ControllerIntegration

  # ...
end

class BarsController < ApplicationController
  include Messaging::ControllerIntegration

  # ...
end

Use a partial to share the view code for displaying the messages. Not for actually fetching them!

# app/views/messages/_partial_name.html.erb
<%= messages.each do |m| %>
  # ...
<% end %>

# app/views/foos/show.html.erb
<%= render partial: 'messages/partial_name', messages: @messages %>

# app/views/bars/show.html.erb
<%= render partial: 'messages/partial_name', messages: @messages %>

Upvotes: 2

Related Questions