开发者

Is it possible to dynamically assign another accessor to an instance variable and have it persist across new instances?

开发者 https://www.devze.com 2023-04-10 02:07 出处:网络
I have a situation where I\'m importing feeds from multiple sources, and have to deal with the fact that attributes are not consistant across feeds.So for an example of some attributes, my site would

I have a situation where I'm importing feeds from multiple sources, and have to deal with the fact that attributes are not consistant across feeds. So for an example of some attributes, my site would like to recognize these in a product:

name, description, category, url

And then have Feed 1 map up, even though it's attributes are:

product_name, descript, category_primary, product_url

And Feed 2 has attributes:

Product, Description, CategoryFirst, URLToProduct

So I can import all prod开发者_StackOverflowucts into a mongoid table using the field names dynamically as they appear in the feed. I could then have a page that allows a admin to map feed attribute names to global attribute names. But what is the easiest way to map the global attribute names to the feed specific ones? In other words I'd like to say Feed.find(id).products.name and have it retrieve the value given the feed specific attribute name (whether that is "product_name" or "Product" or whatever else_


You can have a different model to allow admin to configure feeds. This model just saves the field names of incoming feed attributes mapping to your product and converts a feed item to a product.

class FeedToProductConverter
  include Mongoid::Document

  field :converter_name, :type => String
  field :name, :type => String
  field :description, :type => String
  field :category, :type => String
  field :url, :type => String

  def convert(feed_item)
    p = Product.new
    p.name = feed_item[self.name]
    p.description = feed_item[self.description]
    p.category = feed_item[self.category]
    p.url = feed_item[self.url]

    p
  end

  def convert_and_save(feed_item)
    convert(feed_item).save
  end
end

Now you take inputs from admin and store them. Whenever admin wants to import a feed, s/he selects the appropriate converter and in the backend you utilize it to convert the feed items to your own products. Using any product just like as you desire later on.

0

精彩评论

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

关注公众号