ruby-on-railsrubyhelperservice-object

rails4 using helper/service and where to put it


I created this class for assembling the text based on the length of the product attributes for sharing on twitter.

My questions:

show.html.erb

<a class="twitter-share" data-behavior="twitter-share" 
                         data-twittertext="<%= @product.twitter_share_text %>" 
                         data-twitterurl="<%= product_url(@product) %>" 
                         data-twitteranchor>
  <i class="fa fa-lg fa-twitter"></i>
</a>

product.rb

def twitter_share_text
  TwitterProductShare.new(self).return_text
end

app/services/twitter_product_share.rb

class TwitterProductShare
  URL_LENGTH = 23 #defined by twitter API
  SPACE_LENGTH = 1
  TWITTER_MAX = 140
  attr_reader :name, :oneliner

  def initialize(product)
    @name = product.name
    @oneliner = product.oneliner
  end

  def return_text
    if full_length <= TWITTER_MAX
      return basic_text
    else
      return basic_text[0...-(difference + text_end.length)] + text_end
    end
  end

  private

    def basic_text
      "#{name}: #{oneliner}"
    end

    def difference
      full_length - TWITTER_MAX
    end

    def full_length
      basic_text.length + SPACE_LENGTH + URL_LENGTH
    end

    def text_end
      "..."
    end
end

Solution

  • I think code like that belongs into a view helper:

    # in app/helpers/product_helper.rb
    def twitter_share_link(product)
      data = {
        behavior:      'twitter-share',
        twittertext:   TwitterProductShare.new(product).return_text,
        twitterurl:    product_url(product),
        twitteranchor: 'twitteranchor'
      }
    
      link_to(class: 'twitter-share', data: data) do
        tag(:i, class: 'fa fa-lg fa-twitter')
      end
    end
    

    In your view use this helper like this:

    <%= twitter_share_link(@product) %>
    

    Or you could even return the whole data hash from the TwitterProductShare.