I created this class for assembling the text based on the length of the product attributes for sharing on twitter.
My questions:
- Is this the good approach to tackle the problem? If not this then what? (where should I put the class and the methods, how to invoke it, etc.)
- If this is the good approach then what should be changed? For instance I feel the
def twitter_share_text
shouldn't be in theproduct.rb
.
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