Last active
May 12, 2022 22:35
-
-
Save joalbertg/934bdeb1728d48f379d2b01524e426a0 to your computer and use it in GitHub Desktop.
Initialize objects with default values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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