开发者

Filter an array of hashes within a hash in ruby/rails

I'm aggregating RSS feeds using FeedTools. I followed this tutorial: http://simonwoodside.com/weblog/2008/12/7/ruby_on_rails_feedrss_aggregator/ and everything functioned fine.

The problem is I want to filter some of the hashes that exist within the array [:items] from inside the parsed feed hash.

Here's the RSS cached feed object in my database:

  create_table "cached_feeds", :force => true do |t|
    t.string   "uri"
    t.text     "parsed_feed"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

In script/console the parsed feed looks something like this:

parsed_feed: {:uri => "http://www.someblog.com",
:items =>
[ {:published_at => some date,
  :link => "http://www.someblog.com/somelink.html",
  :title => "Some Title"},

  {:published_at => another date,
  :link => "http://www.someblog.com/anotherlink.html",
  :title => "Another Title"} ]
}

As you can see there are two hashes for parsed_feed, :uri and :items. :items has all the feed item details stashed in a big array of hashes.

Now lets say that "Some Title" is already the name of an article in the database. The purpose of the RSS feed list of items is to tell the user which articles in their RSS feed haven't been uploaded into the db yet, so I only want "Another Title" to show in the view.

This method in the controller 开发者_运维问答does a good job showing all the items without a filter:

def read_cache
    website_articles = @website.article_names.to_a #This would return ["Some Title"]
    @@uris = ["#{Website.find(params[:id]).feed}"]
    @@uris.map { |uri|
    feed = CachedFeed.find_by_uri( uri ).parsed_feed
    feed[:items].map { |item| {:feed_title => @@title_map[feed[:title]] || feed[:title],   :feed_item => item} }
    } .flatten.sort_by { |item| item[:feed_item][:published] } .reverse
  end

I tried to insert this code after .flatten as a filter

.reject {|k,v| website_articles.include? v}

This would work if I was filtering a normal hash, but filtering from an array of hashes within a hash. What am I missing? How can I get "Another Title" to appear in the view without "Some Title" appearing?


Since v in your reject is a hash like { :feed_title => "Some Title", ... }, this ought to work:

.reject {|k, v| website_articles.include? v[:feed_title] }


@Jordan

I got a nil back when I did that. However, your answer did get me on the right track.

Did a little tinkering and apparently I didn't need two variables for the hash:

.reject {|item| website_articles.include? item[:feed_item][:title]}

Thanks for getting me on the right track!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜