Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise way to write a series of one-line methods in Ruby?

Tags:

ruby

Sometimes we end up writing several methods something like:

module XyzGateway
  module Defaults
    def pull_sample asynch=true
      'N/A'
    end

    def is_pull_available?
      false
    end

    def is_push_available?
      true
    end

    def connect params
      logger.debug "Invalid gateway(#{self.id}), could not resolve its type. #{ap self}"
    end

    def gateway_init
    end

    def disconnect
    end
  end
end

I am simply looking for a way to avoid these def and end keywords in such cases, is there any way out? In my case above, these are default behaviors and I would love if I could avoid these def, end.

Edit: yes, actually I do have a module XyzGateway::Defaults for all these.

like image 281
Amol Pujari Avatar asked Sep 05 '25 03:09

Amol Pujari


1 Answers

You cannot avoid them, except by using define_method:

define_method :is_pull_available? { false }

If your goal is just to shorten your code though, you can put the whole method on one line, which isn't so bad for extremely short methods (the fourth method here is probably a bit too long and condensing it like this hurts readability, IMO):

def pull_sample(asynch = true); 'N/A'; end
def is_pull_available?; false; end
def is_push_available?; true; end
def connect params; logger.debug "Invalid gateway(#{self.id}), could not resolve its type. #{ap self}"; end
def gateway_init; end
def disconnect; end
like image 114
Andrew Marshall Avatar answered Sep 07 '25 21:09

Andrew Marshall