Reputation: 21533
I fetch data in json
to create in my webapp, like this
response.each do |article|
title = article['title']
url = article['url']
content = article['content']
image_url = article['image_url']
source = article['source']
created_at = article['created_at']
twitter_share = article['twitter_share']
facebook_share = article['facebook_share']
pocket_share = article['pocket_share']
article = Article.new(title: title, url: url, image_url: image_url, content: content, created_at: created_at, source: source,
twitter_share: twitter_share, facebook_share: facebook_share, pocket_share: pocket_share)
if article.save
puts article.title
end
end
As you can see, there are a lot of duplications, how can I elegantly reduce these duplications?
Upvotes: 2
Views: 53
Reputation: 614
Seems that article is a hash, so you can simple do
response.each do |article|
article = Article.new(article)
if article.save
puts article.title
end
end
If article contains other attributes you can strip them:
allowed = ['title', 'url', 'source']
response.each do |article|
article = Article.new(article.slice(*allowed))
if article.save
puts article.title
end
end
Upvotes: 4
Reputation: 3311
You can use following code:
def permitted_article_attrs_hash(hash)
hash.dup.keep_if do |key, value|
%w(title url content image_url source created_at twitter_share facebook_share pocket_share).include?(key)
end
end
response.each do |article|
article = Article.new(permitted_article_attrs_hash(article))
if article.save
puts article.title
end
end
Advantage of this code is that unpermitted values are removed from article hash.
Upvotes: 2
Reputation: 6100
Why don just use hash you get to create new aricle
response.each do |article|
new_article = Article.new(article)
if new_article.save
puts new_article.title
end
end
Upvotes: 2