Ruby Class refactoring quick reference

I wrote this class that returns feed updates, but I think that it can be further improved. This is not buggy or something else, but as a new ruby โ€‹โ€‹developer, I find it always useful to improve :-)

class FeedManager attr_accessor :feed_object, :update, :new_entries require 'feedtosis' def initialize(feed_url) @feed_object = Feedtosis::Client.new(feed_url) fetch end def fetch @feed_object.fetch end def update @updates = fetch end def updated? @updates.new_entries.count > 0 ? true : false end def new_entries @updates.new_entries end end 

As you can see, this is pretty simple, but what I see is not entirely true:

  • Whenever I call fetch through the terminal, it prints an update list when it really needs to return an object.

So, for example, in the terminal, if I do something like:

 client = Feedtosis::Client.new('http://stackoverflow.com/feeds') result = client.fetch 

Then I get:

 <Curl::Easy http://stackoverflow.com/feeds> 

This is exactly what I expected. However, doing the same with the "inniting" class with:

 FeedManager.new("http://stackoverflow.com/feeds") 

I get an object returning as an array with all the elements in the feed.

Of course, I am doing something wrong, so any help in refactoring this class will be greatly appreciated.

In addition, I would like to see comments about my implementation, as well as any comments to make it better. We greet you.

Thanks in advance

+4
source share
3 answers

Try the following:

 class FeedManager require 'feedtosis' attr_accessor :feed_object def initialize(feed_url) self.feed_object = Feedtosis::Client.new(feed_url) end def fetch feed_object.fetch end def updates (reload = true) @updates = reload ? fetch : @updates end def updated? updates(false).new_entries.count > 0 end def new_entries updates(false).new_entries end end 

Now you can get updates as follows:

 result = FeedManager.new("http://stackoverflow.com/feeds").updates 

PS: I removed attr_accessor for: update and: new_entries.

Edit

I added code to enable conditional cache reloading.

 feed = FeedManager.new("http://stackoverflow.com/feeds") updates = feed.updates # reloads the updates # do something updates = feed.updates(false) # get the updates from cache. 
+1
source

It looks like you expect the initialize method to return the result of the call. Initialization is basically a constructor in Ruby, so it will return a new FeedManager object.

It is also very โ€œunusualโ€ to place a require request in the middle of a class definition.

0
source
  • :update , @updates

  • count > 0 ? true : false count > 0 ? true : false maybe just count > 0

0
source

Source: https://habr.com/ru/post/1304674/


All Articles