Ruby Metaprogramming

Hi, I am working with a project where I am writing the following code:-

store_fb_other_information(profile_obj, "activity", fb_activities, provider, :activity, profile_obj.activity_information, ActivityInformation) #Book Information store_fb_other_information(profile_obj, "book", fb_books, provider, :book, profile_obj.book_information, BookInformation) #Interest Information store_fb_other_information(profile_obj, "interest", fb_interests, provider, :interest, profile_obj.interest_information, InterestInformation) #Movie Information store_fb_other_information(profile_obj, "movie", fb_movies, provider, :movie, profile_obj.movie_information, MovieInformation)

If you look at the code I am calling the same function multiple times only parameters are different.

Can I refactor the above code using metaprogramming If yes how?

Thanks, Mike

Hi, I am working with a project where I am writing the following code:-

store_fb_other_information(profile_obj, "activity", fb_activities, provider, :activity, profile_obj.activity_information, ActivityInformation) #Book Information store_fb_other_information(profile_obj, "book", fb_books, provider, :book, profile_obj.book_information, BookInformation)

[...]

Can I refactor the above code using metaprogramming If yes how?

Hi there. I hope this helps...

I think you could make this work several ways but in any case it looks to me that you only need to pass to store_fb_other_information a couple of things to make this whole thing work. For example:

store_fb_other_information(profile_obj, provider, model) # where model could be an instance of Activity, Book, etc. if you have them or store_fb_other_information(profile_obj, provider, ModelName) # where ModelName could be the class name for Activity, Book, etc. if such models exist or store_fb_other_information(profile_obj, provider, ModelInformation) # where ModelInformation could be the class name for ActivityInformation, BookInformation, etc. which seems to exist or store_fb_other_information(profile_obj, provider, model_name) # where model_name is a string such as 'activity', 'book'

My preferred option would be the first one (if those models actually exist and you instantiate them) because it would be the easiest in my opinion. Any other option would be a slight variation on this one, though. So say you have an activity object:

store_fb_other_information(profile_obj, provider, activity)

def store_fb_other_information(profile, provider, model)

  # if you need the second parameter as a string   model_name = model.class.to_s.downcase

  # if you need to get to fb_activities   model.send("fb_#{model_name.pluralize}")

  # you already have provider

  # if you need the model name as a symbol   model_name.to_sym

  # if you need to get to the profile_object.model_information   profile_obj.send("#{model_name}_information")

end