Skip to content

Service

Georgy Yuriev edited this page May 15, 2018 · 5 revisions

Service is a class with collection of methods. It can be useful when using internal services.

How does it work?

Often we need to use some counters. It can be any limiters, counters of views and so much more. Let's try to create a service for it.

Run rails g service counter It will create new file: 'app/services/counter_service.rb'.

Redis is a good place for storing counters. Let's define our client for the service:

# app/services/counter_service.rb
class CounterService < Methodist::Service
  client Redis.new(host: "localhost", port: 6380, db: 15) # Pass a redis instance here
  # Other code here.
end

Next we should define some methods which can be necessary for our counters. Let's implement three methods:

  • increment
  • fetch
  • clear

Define methods:

# app/services/counter_service.rb
class CounterService < Methodist::Service
  client Redis.new(host: "localhost", port: 6380, db: 15) # Pass a redis instance here
  
  attr_reader :counter_name

  def initialize(counter_name)
    @counter_name = counter_name
  end
  
  def increment
    current_value = fetch
    new_value = current_value + 1
    client.set(counter_name, new_value)
  end

  def fetch
    client.get(counter_name) || 0
  end

  def clear
    client.del(counter_name)
  end
end

Now we can use our service to count page views:

page_view_counter = CounterService.new(:page_view)
page_view_counter.increment
page_view_counter.fetch #> 1
page_view_counter.increment
page_view_counter.fetch #> 2
page_view_counter.clear
page_view_counter.fetch #> 0

Clone this wiki locally