I have a plain ruby class Espresso::MyExampleClass
.
module Espresso
class MyExampleClass
def my_first_function(value)
puts "my_first_function"
end
def my_function_to_run_before
puts "Running before"
end
end
end
With some of the methods in the class, I want to perform a before
or after
callback similar to ActiveSupport callbacks before_action
or before_filter
. I'd like to put something like this in my class, which will run my_function_to_run_before
before my_first_function
:
before_method :my_function_to_run_before, only: :my_first_function
The result should be something like:
klass = Espresso::MyExampleClass.new
klass.my_first_function("yes")
> "Running before"
> "my_first_function"
How do I use call backs in a plain ruby class like in Rails to run a method before each specified method?
Edit2:
Thanks @tadman for recommending XY problem. The real issue we have is with an API client that has a token expiration. Before each call to the API, we need to check to see if the token is expired. If we have a ton of function for the API, it would be cumbersome to check if the token was expired each time.
Here is the example class:
require "rubygems"
require "bundler/setup"
require 'active_support/all'
require 'httparty'
require 'json'
module Espresso
class Client
include HTTParty
include ActiveSupport::Callbacks
def initialize
login("admin@example.com", "password")
end
def login(username, password)
puts "logging in"
uri = URI.parse("localhost:3000" + '/login')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(username: username, password: password)
response = http.request(request)
body = JSON.parse(response.body)
@access_token = body['access_token']
@expires_in = body['expires_in']
@expires = @expires_in.seconds.from_now
@options = {
headers: {
Authorization: "Bearer #{@access_token}"
}
}
end
def is_token_expired?
#if Time.now > @expires.
if 1.hour.ago > @expires
puts "Going to expire"
else
puts "not going to expire"
end
1.hour.ago > @expires ? false : true
end
# Gets posts
def get_posts
#Check if the token is expired, if is login again and get a new token
if is_token_expired?
login("admin@example.com", "password")
end
self.class.get('/posts', @options)
end
# Gets comments
def get_comments
#Check if the token is expired, if is login again and get a new token
if is_token_expired?
login("admin@example.com", "password")
end
self.class.get('/comments', @options)
end
end
end
klass = Espresso::Client.new
klass.get_posts
klass.get_comments