Skip to content

Instantly share code, notes, and snippets.

@joalbertg
Last active May 12, 2022 22:35
Show Gist options
  • Save joalbertg/934bdeb1728d48f379d2b01524e426a0 to your computer and use it in GitHub Desktop.
Save joalbertg/934bdeb1728d48f379d2b01524e426a0 to your computer and use it in GitHub Desktop.
Initialize objects with default values
require 'pry'
require 'pry-nav'
class Application
def self.call(*args, &)
new(*args, &).call
end
private
def response(success: false, payload: {}, error: nil)
Struct.new('Response', :success?, :payload, :error) unless Struct::const_defined?('Response')
Struct::Response.new(success, payload, error)
end
end
# quickstart
#
# ruby article.rb
require_relative 'application.rb'
require 'pry'
require 'pry-nav'
class Article < Application
attr_accessor :params
def initialize(name = '')
@name = name
yield(self) if block_given?
return if params.nil?
@attr_0 = params[:attr_0]
@attr_1 = params[:attr_1]
end
def call
puts "name: #{name}"
puts "params: #{params}"
puts "attr_0: #{attr_0}"
puts "attr_1: #{attr_1}"
response(success: true, payload: { name:, attr_0:, attr_1: })
end
private
attr_reader :name, :attr_0, :attr_1
end
obj = Article.call('Joa') do |a|
a.params = {
attr_0: 'attr_0',
attr_1: 'attr_1'
}
end
puts obj.success?
puts obj.payload
name: Joa
params: {:attr_0=>"attr_0", :attr_1=>"attr_1"}
attr_0: attr_0
attr_1: attr_1
true
{:name=>"Joa", :attr_0=>"attr_0", :attr_1=>"attr_1"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment