source stringclasses 1
value | repo stringlengths 5 63 | repo_url stringlengths 24 82 | path stringlengths 5 167 | language stringclasses 1
value | license stringclasses 5
values | stars int64 10 51.4k | ref stringclasses 23
values | size_bytes int64 200 258k | text stringlengths 137 258k |
|---|---|---|---|---|---|---|---|---|---|
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter09/01-memomer.rb | Ruby | mit | 206 | main | 681 | module Memomer
def self.extended(klass)
mod = Module.new
klass.prepend(mod)
klass.instance_variable_set(:@memomer_mod, mod)
end
def memoize(arg)
iv = :"@memomer_#{arg}"
@memomer_mod.define_method(arg) do
if instance_variable_defined?(iv)
return instance_variable_get(iv)
en... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter09/09-struct-50-method-missing.rb | Ruby | mit | 206 | main | 259 | class Struct50
def method_missing(meth, *)
@fields.fetch(meth){super}
end
def respond_to_missing?(meth, *)
@fields.include?(meth)
end
end
Struct50.new.respond_to?(:valid_field)
# false when using method_missing without
# respond_to_missing? |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter09/04-hash-accessor.rb | Ruby | mit | 206 | main | 898 | module HashAccessor
def hash_accessor(iv, *fields)
fields.each do |field|
define_method(field) do
instance_variable_get(iv)[field]
end
define_method(:"#{field}=") do |v|
instance_variable_get(iv)[field] = v
end
end
end
end
class FooStruct
def initialize(**kwargs)
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter09/00-metastruct.rb | Ruby | mit | 206 | main | 256 | class MetaStruct
def self.method_missing(meth, arg=nil, &block)
block ||= proc{arg}
define_method(meth, &block)
end
end
class A < MetaStruct
b
foo 1
bar{3.times.map{foo}}
end
A.new.b
# => nil
A.new.foo
# => 1
A.new.bar
# => [1, 1, 1] |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter09/08-words.rb | Ruby | mit | 206 | main | 263 | def words(&block)
array = []
Class.new(BasicObject) do
define_method(:method_missing) do |meth, *|
array << meth
end
end.new.instance_exec(&block)
array.reverse
end
words{this is a list of words}
# => [:this, :is, :a, :list, :of, :words] |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter09/chapter-09.rb | Ruby | mit | 206 | main | 5,030 | ### 9
### Metaprogramming and When to Use It
## Learning the pros and cons of abstraction
class A
def b
nil
end
end
# --
def_class = ->(sym, method_hash) do
c = Object.const_set(sym, Class.new)
method_hash.each do |meth, val|
c.define_method(meth){val}
end
end
def_class.call(:A, b: nil)
# --
cl... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter10/01-foo-process-bars.rb | Ruby | mit | 206 | main | 1,075 | Foo.process_bars(
[:bar1, :baz2, 3, {quux: 1}],
[:bar2, :baz4, 5],
# ...
skip_check: ->(bar){bar.number == 5},
generate_names: true
)
bar1 = Bar.new(:bar1, :baz2, 3, quux: 1)
bar2 = Bar.new(:bar2, :baz4, 5)
command = ProcessBarCommand.new
command.add_bar(bar1)
command.add_bar(bar2)
# ...
command.skip_check{... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter10/00-rspec.rb | Ruby | mit | 206 | main | 711 | RSpec.configure do |c|
c.drb = true
c.drb_port = 24601
c.around do |spec|
DB.transaction(rollback: :always, &spec)
end
end
RSpec::Core::DRbRunner.new(port: 24601)
RSpec::Core::Hooks.register(:prepend, :around) do |spec|
DB.transaction(rollback: :always, &spec)
end
module RSpec
self.drb = true
self... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter10/chapter-10.rb | Ruby | mit | 206 | main | 3,782 | ### 10
### Designing Useful Domain Specific Languages
## Designing your domain-specific language
RSpec.configure do |c|
c.drb = true
c.drb_port = 24601
c.around do |spec|
DB.transaction(rollback: :always, &spec)
end
end
# --
RSpec::Core::DRbRunner.new(port: 24601)
RSpec::Core::Hooks.register(:prepend,... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter10/02-sequel.rb | Ruby | mit | 206 | main | 569 | DB[:table].where(Sequel[:column] > 11)
# generates SQL: SELECT * FROM table WHERE (column > 11)
DB[:table].where{column > 11}
@some_var = 10
DB[:table].where{column > @some_var}
@some_var = 10
DB[:table].where{|o| o.column > @some_var}
class Sequel::Dataset
def where(&block)
cond = if block.arity == 1
y... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter10/03-minitest.rb | Ruby | mit | 206 | main | 697 | require 'minitest/autorun'
describe Class do
before do
# setup code
end
after do
# teardown code
end
it "should allow creating classes via .new" do
Class.new.must_be_kind_of Class
end
end
module Kernel
def describe(name, *, &block)
klass = Class.new(Minitest::Spec)
klass.name = na... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter10/04-sinatra.rb | Ruby | mit | 206 | main | 311 | require 'sinatra'
get "/" do
"Index page"
end
not_found do
"File Not Found"
end
module Sinatra::Delegator
meths = %i[get not_found] # ...
meths.each do |meth|
define_method(meth) do |*args, &block|
Sinatra::Application.send(meth, *args, &block)
end
end
end
extend Sinatra::Delegator |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/02-input-validation-v3.rb | Ruby | mit | 206 | main | 366 | Fruit = Struct.new(:type, :color, :price)
FRUITS = {}
FRUITS[1] = Fruit.new('apple', 'red', 0.70)
FRUITS[2] = Fruit.new('pear', 'green', 1.23)
FRUITS[3] = Fruit.new('banana', 'yellow', 1.40)
Roda.route do |r|
r.get "fruit", Integer, String do |fruit_id, field|
next unless %w[type color price].include?(field)
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/03-input-validation-v4.rb | Ruby | mit | 206 | main | 539 | Fruit = Struct.new(:type, :color, :price)
FRUITS = {}
FRUITS[1] = Fruit.new('apple', 'red', 0.70)
FRUITS[2] = Fruit.new('pear', 'green', 1.23)
FRUITS[3] = Fruit.new('banana', 'yellow', 1.40)
Roda.route do |r|
r.is "fruit", Integer, String do |fruit_id, field|
r.get do
next unless %w[type color price].incl... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/01-input-validation-v2.rb | Ruby | mit | 206 | main | 363 | Fruit = Struct.new(:type, :color, :price)
FRUITS = {}
FRUITS[1] = Fruit.new('apple', 'red', 0.70)
FRUITS[2] = Fruit.new('pear', 'green', 1.23)
FRUITS[3] = Fruit.new('banana', 'yellow', 1.40)
Roda.route do |r|
r.get "fruit", Integer, String do |fruit_id, field|
next if field == "exit"
FRUITS[fruit_id].send(f... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/05-access-control-rails-before-action.rb | Ruby | mit | 206 | main | 407 | class FooController < ApplicationController
before_action :check_access
def index
# ...
end
def create
# ...
end
# ...
private def check_access
# ...
end
end
class FooController < ApplicationController
before_action :check_access, only: [:create]
# ...
end
class FooController < App... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/00-input-validation-v1.rb | Ruby | mit | 206 | main | 334 | Fruit = Struct.new(:type, :color, :price)
FRUITS = {}
FRUITS[1] = Fruit.new('apple', 'red', 0.70)
FRUITS[2] = Fruit.new('pear', 'green', 1.23)
FRUITS[3] = Fruit.new('banana', 'yellow', 1.40)
Roda.route do |r|
r.get "fruit", Integer, String do |fruit_id, field|
FRUITS[fruit_id].send(field).to_s
end
end
# GET ... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/06-access-control-rails-skip-before-action.rb | Ruby | mit | 206 | main | 214 | class ApplicationController < ActionController::Base
before_action :require_login
# ...
end
class BarController < ApplicationController
skip_before_action :require_login, only: [:index, :bars]
# ...
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/chapter-17.rb | Ruby | mit | 206 | main | 3,236 | ### 17
### Robust Web Application Security
## Trusting input never
Fruit = Struct.new(:type, :color, :price)
# --
FRUITS = {}
FRUITS[1] = Fruit.new('apple', 'red', 0.70)
FRUITS[2] = Fruit.new('pear', 'green', 1.23)
FRUITS[3] = Fruit.new('banana', 'yellow', 1.40)
# --
Roda.route do |r|
r.get "fruit", Integer, St... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter17/04-input-validation-v5.rb | Ruby | mit | 206 | main | 572 | Fruit = Struct.new(:type, :color, :price)
FRUITS = {}
FRUITS[1] = Fruit.new('apple', 'red', 0.70)
FRUITS[2] = Fruit.new('pear', 'green', 1.23)
FRUITS[3] = Fruit.new('banana', 'yellow', 1.40)
Roda.route do |r|
r.is "fruit", Integer, String do |fruit_id, field|
r.get do
next unless %w[type color price].incl... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/06-rest-arguments.rb | Ruby | mit | 206 | main | 589 | def foo(bar, *)
end
def foo(bar, *)
bar = 2
super
end
def a(*bar)
end
def a(bar)
end
def a(bar=[])
end
EMPTY_ARRAY = [].freeze
def a(bar=EMPTY_ARRAY)
end
EMPTY_ARRAY = [].freeze
def a(bar=EMPTY_ARRAY)
bar << 1
end
EMPTY_ARRAY = [].freeze
def a(bar=EMPTY_ARRAY)
bar = bar.dup
bar << 1
end
a(:foo, :bar)
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/18-forwardable.rb | Ruby | mit | 206 | main | 245 | require 'forwardable'
class A
extend Forwardable
def_delegators :b, :foo
end
class A
extend Forwardable
def_delegators :@b, :foo
def_delegators "A::B", :foo
end
class A
extend Forwardable
def_delegators :b, :foo, :bar, :baz
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/14-constant-visibility.rb | Ruby | mit | 206 | main | 430 | class ConstantVis
PRIVATE = 1
private_constant :PRIVATE
end
ConstantVis::PRIVATE
# NameError
# --
class ConstantVis
def self.const_missing(const)
if const == :PRIVATE
warn("ConstantVis::PRIVATE is a private constant, " \
"stop accessing it!", uplevel: 1)
return PRIVATE
end
su... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/07-keyword-arguments.rb | Ruby | mit | 206 | main | 2,573 | # Hash
foo({:bar=>1})
# Hash (without braces)
foo(:bar=>1)
def foo(options)
end
def foo(options={})
end
OPTIONS = {}.freeze
def foo(options=OPTIONS)
end
foo(:bar=>1)
BAR_OPTIONS = {:bar=>1}.freeze
foo(BAR_OPTIONS)
def foo(options=OPTIONS)
bar = options[:bar]
end
# :baz keyword ignored
foo(:baz=>2)
def foo(op... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/05-positional-argument-types.rb | Ruby | mit | 206 | main | 350 | def a(x, y=2, z)
[x, y, z]
end
a(1, 3)
# => [1, 2, 3]
eval(<<END)
def a(x=1, y, z=2)
end
END
# SyntaxError
def a(x, y=2, z)
end
eval(<<END)
def a(x=1, y, z=2)
end
END
def a(x, y=nil)
end
def a(x=nil, y)
end
def a(y)
end
a(2)
def a(x=nil, y)
end
a(1, 2)
def identifier(column, table=nil)
end
def iden... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/08-block-arguments.rb | Ruby | mit | 206 | main | 572 | def foo(bar)
yield(bar, @baz)
end
foo(1) do |bar, baz|
bar + baz
end
def foo(bar)
yield(bar, @baz, @initial || 0)
end
foo(1) do |bar, baz|
bar + baz
end
foo(1) do |bar, baz, initial|
bar + baz + initial
end
adder = -> (bar, baz) do
bar + baz
end
# Worked before, now broken
foo(1, &adder)
def foo(bar,... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/02-screen-box-object.rb | Ruby | mit | 206 | main | 202 | Box = Struct.new(:x1, :y1, :x2, :y2)
class Screen
def draw_box(box)
end
end
screen.draw_box(Box.new(0, 0, 10, 20))
box = Box.new
box.x1 = 0
box.x2 = 10
box.y1 = 0
box.y2 = 20
screen.draw_box(box) |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/17-delegating-to-another-object.rb | Ruby | mit | 206 | main | 347 | class A
attr_accessor :b
def initialize(b)
@b = b
end
end
class A
def foo(*args, **kwargs, &block)
b.foo(*args, **kwargs, &block)
end
end
class A
def foo(...)
b.foo(...)
end
end
class A
def foo(*args, &block)
b.foo(*args, &block)
end
if respond_to?(:ruby2_keywords, true)
ruby... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/04-screen-box-positional-keyword.rb | Ruby | mit | 206 | main | 326 | class Screen
def draw_box(_x1=nil, _y1=nil, _x2=nil, _y2=nil,
x1:_x1, y1:_y1, x2:_x2, y2:_y2)
raise ArgumentError unless x1 && x2 && y1 && y2
end
end
screen.draw_box(0, 10, 0, 20)
screen.draw_box(x1: 0, x2: 0, y1: 0, y2: 20)
screen.draw_box(5, 30, 15, 40,
x1: 0, x2: 0, y1: 0, y2... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/11-listen-v3.rb | Ruby | mit | 206 | main | 340 | def listen(callback: nil)
server.start_listening
yield if block_given?
if callback
while notification = server.receive_notification
callback.(notification)
end
else
server.receive_notification
end
ensure
server.stop_listening
end
listen(callback: ->(notification) do
process_notification... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/chapter-04.rb | Ruby | mit | 206 | main | 10,155 | ### 4
### Methods and Their Arguments
## Understanding that there are no class methods, only instance methods
class Foo
def self.bar
:baz
end
end
# --
class Foo
end
def Foo.bar
:baz
end
# --
def (Foo = Class.new).bar
:baz
end
# --
class Foo
class << self
def bar
:baz
end
end
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/16-delegating-to-another-method.rb | Ruby | mit | 206 | main | 578 | def foo(*args, **kwargs, &block)
[args, kwargs, block]
end
def bar(*args, **kwargs, &block)
[args, kwargs, block]
end
def foo(*args, **kwargs, &block)
warn("foo is being renamed to bar", uplevel: 1)
bar(*args, **kwargs, &block)
end
def foo(...)
warn("foo is being renamed to bar", uplevel: 1)
bar(...)
end... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/00-class-methods.rb | Ruby | mit | 206 | main | 690 | class Foo
def self.bar
:baz
end
end
class Foo
end
def Foo.bar
:baz
end
def (Foo = Class.new).bar
:baz
end
class Foo
class << self
def bar
:baz
end
end
end
# --
class Foo
end
class << Foo
def bar
:baz
end
end
Foo.instance_eval do
def bar
:baz
end
end
class Foo
def... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/10-listen-v2.rb | Ruby | mit | 206 | main | 288 | def listen
server.start_listening
yield if block_given?
server.receive_notification
ensure
server.stop_listening
end
time = nil
notification = listen do
time = Time.now
end
elapsed_seconds = Time.now - time
while notification = listen
process_notification(notification)
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/12-listen-v4.rb | Ruby | mit | 206 | main | 342 | def listen(after_listen: nil)
server.start_listening
after_listen.call if after_listen
if block_given?
while notification = server.receive_notification
yield notification
end
else
server.receive_notification
end
ensure
server.stop_listening
end
listen do |notification|
process_notificat... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter04/13-method-visibility.rb | Ruby | mit | 206 | main | 448 | class MethodVis
protected def foo
:foo
end
end
MethodVis.instance_methods(false)
# => [:foo]
m = MethodVis.new
m.methods.include?(:foo)
# => true
m.foo
# NoMethodError
class MethodVis
private def method_missing(sym, ...)
if sym == :foo
warn("foo is a protected method, stop calling it!",
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/06-null-object-v5.rb | Ruby | mit | 206 | main | 808 | class AbstractEmployee
attr_reader :name
attr_reader :position
attr_reader :phone
def employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{@phone}
Supervisor Name: #{@supervisor.name}
Supervisor Position: #{@supervisor.position}
Supervisor Phone: #{@supervisor.phone}
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/14-adapter.rb | Ruby | mit | 206 | main | 306 | class Adapter
def initialize(conn)
@conn = conn
end
end
class Adapter::M < Adapter
def execute(sql)
@conn.exec(sql)
end
end
class Adapter::P < Adapter
def execute(sql)
@conn.execute_query(sql)
end
end
class Adapter::S < Adapter
def execute(sql)
@conn.exec_sql(sql)
end
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/09-null-object-v8.rb | Ruby | mit | 206 | main | 1,031 | class AbstractEmployee
attr_reader :name
attr_reader :position
attr_reader :phone
def specific_employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{@phone}
END
end
end
class Employee < AbstractEmployee
attr_reader :supervisor
def initialize(name, position, phone, supe... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/11-hashed-arbitrary-visitor-v1.rb | Ruby | mit | 206 | main | 595 | class HashedArbitraryVisitor < ArbitraryVisitor
DISPATCH = {
Integer => :visit_integer,
String => :visit_string,
Array => :visit_array,
}.freeze
def visit(obj)
if meth = DISPATCH[obj.class]
send(meth, obj)
else
raise ArgumentError, "unsupported object visited"
end
end
pri... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/16-adapter-and-strategy.rb | Ruby | mit | 206 | main | 1,154 | class MultiInsert
def initialize(table, rows)
@table = table
@rows = rows
end
end
class MultiInsert::MultipleQueries < MultiInsert
def format_sqls
prefix = "INSERT INTO #{@table} VALUES ("
@rows.map do |row|
["#{prefix}#{row.join(', ')})"]
end
end
end
class MultiInsert::SingleQuery <... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/07-null-object-v6.rb | Ruby | mit | 206 | main | 935 | class AbstractEmployee
attr_reader :name
attr_reader :position
attr_reader :phone
def employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{@phone}
Supervisor Name: #{@supervisor.name}
Supervisor Position: #{@supervisor.position}
Supervisor Phone: #{@supervisor.phone}
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/10-arbitrary-visitor.rb | Ruby | mit | 206 | main | 542 | class ArbitraryVisitor
def visit(obj)
case obj
when Integer
visit_integer(obj)
when String
visit_string(obj)
when Array
visit_array(obj)
else
raise ArgumentError, "unsupported object visited"
end
end
private
def visit_integer(obj)
obj ** obj
end
def vis... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/chapter-13.rb | Ruby | mit | 206 | main | 8,489 | ### 13
### Using Common Design Patterns
## Learning about many design patterns that are built into Ruby
class Foo
end
# --
foo_class = Class.new
foo_class.define_method(:bar) do
2
end
foo_instance = foo_class.new
foo_instance.bar
# => 2
# --
foo_proto = Object.new
foo_proto.define_singleton_method(:bar) do
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/03-null-object-v2.rb | Ruby | mit | 206 | main | 1,014 | class Employee
attr_reader :name
attr_reader :position
attr_reader :phone
def initialize(name, position, phone, supervisor)
@name = name
@position = position
@phone = phone
@supervisor = supervisor
end
def employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/15-strategy.rb | Ruby | mit | 206 | main | 789 | class MultiInsert
def initialize(table, rows)
@table = table
@rows = rows
end
end
class MultiInsert::MultipleQueries < MultiInsert
def format_sqls
prefix = "INSERT INTO #{@table} VALUES ("
@rows.map do |row|
["#{prefix}#{row.join(', ')})"]
end
end
end
class MultiInsert::SingleQuery <... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/08-null-object-v7.rb | Ruby | mit | 206 | main | 661 | class Employee
attr_reader :supervisor
def initialize(name, position, phone, supervisor)
@name = name
@position = position
@phone = phone
@supervisor = supervisor
end
def specific_employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{@phone}
END
end
def e... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/12-hashed-arbitrary-visitor-v2.rb | Ruby | mit | 206 | main | 711 | class HashedArbitraryVisitor
DISPATCH = {
Integer => :visit_integer,
String => :visit_string,
Array => :visit_array,
}.freeze
def visit(obj)
klass = obj.class
if meth = DISPATCH[klass]
send(meth, obj)
else
while klass = klass.superclass
if meth = DISPATCH[klass]
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/02-null-object-v1.rb | Ruby | mit | 206 | main | 907 | class Employee
attr_reader :name
attr_reader :position
attr_reader :phone
def initialize(name, position, phone, supervisor)
@name = name
@position = position
@phone = phone
@supervisor = supervisor
end
def employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/04-null-object-v3.rb | Ruby | mit | 206 | main | 1,190 | class Employee
attr_reader :name
attr_reader :position
attr_reader :phone
def initialize(name, position, phone, supervisor)
@name = name
@position = position
@phone = phone
@supervisor = supervisor
end
def employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter13/05-null-object-v4.rb | Ruby | mit | 206 | main | 740 | class AbstractEmployee
attr_reader :name
attr_reader :position
attr_reader :phone
def employee_info
<<~END
Name: #{@name}
Position: #{@position}
Phone: #{@phone}
Supervisor Name: #{@supervisor.name}
Supervisor Position: #{@supervisor.position}
Supervisor Phone: #{@supervisor.phone}
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter14/01-multiply-prof-v2.rb | Ruby | mit | 206 | main | 767 | class MultiplyProf
def initialize(vals)
v1, v2 = vals
@i1, @i2 = v1.to_i, v2.to_i
@f1, @f2 = v1.to_f, v2.to_f
@r1, @r2 = v1.to_r, v2.to_r
end
def integer
@i1 * @i2
end
def float
@f1 * @f2
end
def rational
@r1 * @r2
end
end
mp = MultiplyProf.new([2.4r, 4.2r])
mp.integer
# =>... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter14/chapter-14.rb | Ruby | mit | 206 | main | 3,479 | ### 14
### Optimizing Your Library
## Profiling first, optimizing second
class MultiplyProf
def initialize(vals)
@i1, @i2 = vals.map(&:to_i)
@f1, @f2 = vals.map(&:to_f)
@r1, @r2 = vals.map(&:to_r)
end
def integer
@i1 * @i2
end
def float
@f1 * @f2
end
def rational
@r1 * @r2
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter14/02-multiply-prof-v3.rb | Ruby | mit | 206 | main | 446 | class MultiplyProf
def initialize(vals)
@vals = vals
end
def integer
@vals[0].to_i * @vals[1].to_i
end
def float
@vals[0].to_f * @vals[1].to_f
end
def rational
@vals[0].to_r * @vals[1].to_r
end
end
require 'benchmark/ips'
Benchmark.ips do |x|
x.report("MultiplyProf") do
Multiply... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter14/04-multiply-prof-v5.rb | Ruby | mit | 206 | main | 458 | class MultiplyProf
def initialize(vals)
@vals = vals
end
def integer
@integer ||= @vals[0].to_i * @vals[1].to_i
end
def float
@float ||= @vals[0].to_f * @vals[1].to_f
end
def rational
@rational ||= @vals[0].to_r * @vals[1].to_r
end
end
Benchmark.ips do |x|
x.report("MultiplyProf") do
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter14/03-multiply-prof-v4.rb | Ruby | mit | 206 | main | 379 | class MultiplyProf
attr_reader :integer
attr_reader :float
attr_reader :rational
def initialize(vals)
v1, v2 = vals
@integer = v1.to_i * v2.to_i
@float = v1.to_f * v2.to_f
@rational = v1.to_r * v2.to_r
end
end
mp = MultiplyProf.new([2.4r, 4.2r])
Benchmark.ips do |x|
x.report("MultiplyProf"... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter14/00-multiply-prof-v1.rb | Ruby | mit | 206 | main | 945 | class MultiplyProf
def initialize(vals)
@i1, @i2 = vals.map(&:to_i)
@f1, @f2 = vals.map(&:to_f)
@r1, @r2 = vals.map(&:to_r)
end
def integer
@i1 * @i2
end
def float
@f1 * @f2
end
def rational
@r1 * @r2
end
end
mp = MultiplyProf.new([2.4r, 4.2r])
mp.integer
# => 8
mp.float
# => ... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/chapter-07.rb | Ruby | mit | 206 | main | 3,776 | ### 7
### Designing Your Library
## Focusing on the user experience
[[1, 2], [3, 4]].to_csv
# => "1,2\n3,4\n"
# --
ToCSV.new([[1, 2], [3, 4]]).csv
# --
ToCSV.csv([[1, 2], [3, 4]])
# --
ToCSV.([[1, 2], [3, 4]])
# --
ToCSV[[[1, 2], [3, 4]]]
## Determining the appropriate size for your library
ToCSV[[[1, 2], [... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/05-complexity-tradeoffs-v6.rb | Ruby | mit | 206 | main | 493 | def first(number: (only_one = 1), offset: 0)
reset
offset.times{next_record}
ary = []
while record = next_record
if !block_given? || yield(record)
ary << record
break if ary.length >= number
end
end
only_one ? ary[0] : ary
end
first
first(number: 3)
first{|rec| rec.id == 10}
first(num... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/04-complexity-tradeoffs-v5.rb | Ruby | mit | 206 | main | 959 | def _first_n_records(number: (only_one = 1), offset: 0)
reset
offset.times{next_record}
ary = []
while record = next_record
if !block_given? || yield(record)
ary << record
break if ary.length >= number
end
end
only_one ? ary[0] : ary
end
def first_record(offset: 0, &block)
_first_n_... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/00-complexity-tradeoffs-v1.rb | Ruby | mit | 206 | main | 1,128 | def first_record
reset
next_record
end
def first_n_records(n)
reset
ary = []
n.times do
break unless record = next_record
ary << record
end
ary
end
def first_matching_record
reset
while record = next_record
if yield record
return record
end
end
nil
end
def first_n_matc... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/01-complexity-tradeoffs-v2.rb | Ruby | mit | 206 | main | 306 | def first_record(offset: 0)
reset
offset.times{next_record}
next_record
end
def record_at_offset(o)
first_record(offset: o)
end
def first_n_records(n, offset: 0)
reset
offset.times{next_record}
ary = []
n.times do
break unless record = next_record
ary << record
end
ary
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/03-complexity-tradeoffs-v4.rb | Ruby | mit | 206 | main | 307 | def first_n_records(number: (only_one = 1), offset: 0)
reset
offset.times{next_record}
ary = []
while record = next_record
if !block_given? || yield(record)
ary << record
break if ary.length >= number
end
end
only_one ? ary[0] : ary
end
alias first_record first_n_records |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter07/02-complexity-tradeoffs-v3.rb | Ruby | mit | 206 | main | 403 | def first_n_records(n, offset: 0)
reset
offset.times{next_record}
ary = []
while record = next_record
if !block_given? || yield(record)
ary << record
break if ary.length >= n
end
end
ary
end
def first_record(offset: 0)
reset
offset.times{next_record}
while record = next_record
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/01-authorizer-return-value.rb | Ruby | mit | 206 | main | 386 | class Authorizer
def self.check(user, action)
new(user, action).authorized?
end
def authorized?
return true if user.admin?
return true if action == :view_own_profile
false
end
end
if Authorizer.check(current_user, :manage_users)
show_manage_users_page
else
show_invalid_access_page
end
Aut... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/04-exception-backtraces.rb | Ruby | mit | 206 | main | 489 | raise ArgumentError, "message"
raise ArgumentError, "message", []
# Earlier, outside the method
EMPTY_ARRAY = [].freeze
# Later, inside a method
raise ArgumentError, "message", EMPTY_ARRAY
exception = ArgumentError.new("message")
raise exception
exception = ArgumentError.new("message")
exception.set_backtrace(EMPT... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/06-add-error-class-as-needed.rb | Ruby | mit | 206 | main | 611 | module Foo
class Error < StandardError
end
def foo(bar)
unless allowed?(bar)
raise Error, "bad bar: #{bar.inspect}"
end
end
end
module Foo
class TransientError < Error
end
end
begin
foo(bar)
rescue Foo::TransientError
sleep(3)
retry
end
begin
foo(bar)
rescue Foo::Error => e
if e.... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/03-authorizor-both.rb | Ruby | mit | 206 | main | 607 | class Authorizer
class InvalidAuthorization < StandardError
end
def self.check(user, action)
unless new(user, action).authorized?
raise InvalidAuthorization,
"#{user.name} is not authorized to perform #{action}"
end
end
def self.allowed?(user, action)
new(user, action).authorized?
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/02-authorizer-exception.rb | Ruby | mit | 206 | main | 516 | class Authorizer
class InvalidAuthorization < StandardError
end
def self.check(user, action)
unless new(user, action).authorized?
raise InvalidAuthorization,
"#{user.name} is not authorized to perform #{action}"
end
end
end
if Authorizer.check(current_user, :manage_users)
show_manage_use... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/chapter-05.rb | Ruby | mit | 206 | main | 7,722 | ### 5
### Handling Errors
## Handling errors with return values
# Python code:
{'a': 2}['b']
# KeyError: 'b'
# --
{'a'=>2}['b']
# => nil
# --
# Python code:
{'a': 2}.get('b', None)
# => None (Python equivalent of Ruby's nil)
# --
{'a'=>2}.fetch('b')
# KeyError (key not found: "b")
# --
hash[key] ||= value
# ... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/00-database-update.rb | Ruby | mit | 206 | main | 209 | def update(pk, column, value)
database.run_update(<<-SQL)
UPDATE table
SET #{column} = #{database.literal(value)}
WHERE id = #{database.literal(pk)}
SQL
end
update(self.id, :name, 'New Name') |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter05/05-broken-circuit.rb | Ruby | mit | 206 | main | 663 | class BrokenCircuit
def initialize(num_failures: 3, within: 60)
@num_failures = num_failures
@within = within
@failures = []
end
def check
if @failures.length >= @num_failures
cutoff = Time.now - @within
@failures.reject!{|t| t < cutoff}
return if @failures.length >= @num_failu... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter16/chapter-16.rb | Ruby | mit | 206 | main | 1,014 | ### 16
### Web Application Design Principles
## Deciding on a web framework
require 'sinatra'
get('/'){'Hello World'}
# --
require 'roda'
Roda.route do |r|
r.root{'Hello World'}
end
## Designing URL paths
class App < Roda
route do |r|
r.on 'forums', Integer do |forum_id|
forum = Forum[forum_id]
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter16/01-flat-routes.rb | Ruby | mit | 206 | main | 549 | class App < Roda
route do |r|
r.on 'forums', Integer do |forum_id|
forum = Forum[forum_id]
unless forum.allow_access?(current_user_id)
response.status = 403
r.halt
end
# ...
end
r.on 'topics', Integer do |topic_id|
topic = Topic[topic_id]
unless topic.... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter16/00-nested-routes.rb | Ruby | mit | 206 | main | 239 | class App < Roda
route do |r|
r.on 'forums', Integer do |forum_id|
forum = Forum[forum_id]
unless forum.allow_access?(current_user_id)
response.status = 403
r.halt
end
# ...
end
end
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/chapter-11.rb | Ruby | mit | 206 | main | 4,098 | ### 11
### Testing to Ensure Your Code Works
## Understanding why testing is so critical in Ruby
Dir['/path/to/dir/**/*.rb'].each do |file|
print file, ': '
system('ruby', '-c', '--disable-gems', file)
end
# --
Dir['/path/to/dir/**/*.rb'].each do |file|
read, write = IO.pipe
print '.'
system('ruby', '-c',... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/05-code-coverage.rb | Ruby | mit | 206 | main | 388 | class Foo
attr_accessor :bar
def branch(v)
v > 1 ? bar : baz
end
def baz; raise; end
end
describe Foo do
it "#branch should return the value of bar" do
foo = Foo.new
foo.bar = 3
(foo.branch(2)).must_equal 3
end
end
describe Foo do
it "#branch should return the value of bar" do
Foo.... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/01-whichfaster-tad.rb | Ruby | mit | 206 | main | 319 | class WhichFaster
def faster_one(callable1, callable2)
t1 = time{callable1.call}
t2 = time{callable2.call}
t1 > t2 ? callable2 : callable1
end
private def time
t = clock_time
yield
clock_time - t
end
private def clock_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/02-whichfaster-tdd.rb | Ruby | mit | 206 | main | 744 | describe WhichFaster do
it "returns faster callable" do
which = WhichFaster.new
c1 = which.callable1 = ->{a}
c2 = which.callable2 = ->{b}
which.timer = {c1=>1, c2=>2}
_(which.faster_one).must_equal c1
which.timer = {c1=>2, c2=>1}
_(which.faster_one).must_equal c2
end
end
class WhichFa... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/00-syntax-checking.rb | Ruby | mit | 206 | main | 671 | Dir['/path/to/dir/**/*.rb'].each do |file|
print file, ': '
system('ruby', '-c', '--disable-gems', file)
end
Dir['/path/to/dir/**/*.rb'].each do |file|
read, write = IO.pipe
print '.'
system('ruby', '-c', '--disable-gems', file,
out: write, err: write)
write.close
output = read.read
unless out... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/04-unit-testing.rb | Ruby | mit | 206 | main | 399 | class Foo
singleton_class.alias_method(:build, :new)
def build_foo(arg)
Foo.build(arg)
end
end
describe Foo do
it "#build_foo should call Foo.build" do
mock = Minitest::Mock.new
mock.expect :call, :foo, [1]
Foo.stub :build, mock do
_(Foo.new.build_foo(1)).must_equal :foo
end
mo... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter11/03-test-complexity.rb | Ruby | mit | 206 | main | 927 | describe Foo do
it "should have bar return a Bar instance" do
_(Foo.new.bar).must_be_kind_of(Bar)
end
it "should have baz return a Baz instance" do
_(Foo.new.baz).must_be_kind_of(Baz)
end
it "should have quux return a Quux instance" do
_(Foo.new.quux).must_be_kind_of(Quux)
end
end
describe Fo... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/10-plugin-system-v8.rb | Ruby | mit | 206 | main | 3,009 | class Libry
class Book; end
class User; end
PLUGINS = {}
def self.register_plugin(symbol, mod)
PLUGINS[symbol] = mod
end
def self.inherited(subclass)
subclass.const_set(:Book, Class.new(self::Book))
subclass.const_set(:User, Class.new(self::User))
end
module Plugins
module Core
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/01-regular-classes-cursed-book-singleton-method.rb | Ruby | mit | 206 | main | 692 | class Libry
class User
def initialize(id)
@id = id
@books = []
end
def checkout(book)
book.checked_out_to = self
@books << book
end
attr_accessor :books
end
class Book
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/06-plugin-system-v4.rb | Ruby | mit | 206 | main | 1,975 | class Libry
class Book; end
class User; end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete(self)
@checked_out_to = nil
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/05-plugin-system-v3.rb | Ruby | mit | 206 | main | 1,808 | class Libry
class Book; end
class User; end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete(self)
@checked_out_to = nil
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/02-regular-classes-cursed-book-extend.rb | Ruby | mit | 206 | main | 810 | class Libry
class User
def initialize(id)
@id = id
@books = []
end
def checkout(book)
book.checked_out_to = self
@books << book
end
attr_accessor :books
end
class Book
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/08-plugin-system-v6.rb | Ruby | mit | 206 | main | 2,283 | class Libry
class Book; end
class User; end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete(self)
@checked_out_to = nil
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/chapter-08.rb | Ruby | mit | 206 | main | 8,567 | ### 8
### Designing for Extensibility
## Using Ruby's extensibility features
class Libry
class User
def initialize(id)
@id = id
@books = []
end
attr_accessor :books
end
class Book
def initialize(name)
@name = name
end
attr_accessor :checked_out_to
end
end
# --
clas... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/11-plugin-system-v9.rb | Ruby | mit | 206 | main | 3,270 | class Libry
class Book; end
class User; end
PLUGINS = {}
def self.register_plugin(symbol, mod)
PLUGINS[symbol] = mod
end
def self.inherited(subclass)
subclass.const_set(:Book, Class.new(self::Book))
subclass.const_set(:User, Class.new(self::User))
end
module Plugins
module Core
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/03-plugin-system-v1.rb | Ruby | mit | 206 | main | 974 | class Libry
class Book; end
class User; end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete(self)
@checked_out_to = nil
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/09-plugin-system-v7.rb | Ruby | mit | 206 | main | 2,719 | class Libry
class Book; end
class User; end
PLUGINS = {}
def self.register_plugin(symbol, mod)
PLUGINS[symbol] = mod
end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/12-globally-frozen-locally-mutable.rb | Ruby | mit | 206 | main | 3,197 | class Libry
class Book; end
class User; end
PLUGINS = {}
def self.register_plugin(symbol, mod)
PLUGINS[symbol] = mod
end
def self.inherited(subclass)
subclass.const_set(:Book, Class.new(self::Book))
subclass.const_set(:User, Class.new(self::User))
end
module Plugins
module Core
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/07-plugin-system-v5.rb | Ruby | mit | 206 | main | 2,137 | class Libry
class Book; end
class User; end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete(self)
@checked_out_to = nil
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/04-plugin-system-v2.rb | Ruby | mit | 206 | main | 1,476 | class Libry
class Book; end
class User; end
module Plugins
module Core
module BookMethods
attr_accessor :checked_out_to
def initialize(name)
@name = name
end
def checkin
checked_out_to.books.delete(self)
@checked_out_to = nil
end
... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter08/00-regular-classes.rb | Ruby | mit | 206 | main | 479 | class Libry
class User
def initialize(id)
@id = id
@books = []
end
attr_accessor :books
end
class Book
def initialize(name)
@name = name
end
attr_accessor :checked_out_to
end
end
class Libry
class User
def checkout(book)
book.checked_out_to = self
@b... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter02/08-dependency-inversion-current-day-v1.rb | Ruby | mit | 206 | main | 286 | class CurrentDay
def initialize
@date = Date.today
@schedule = MonthlySchedule.new(@date.year,
@date.month)
end
def work_hours
@schedule.work_hours_for(@date)
end
def workday?
!@schedule.holidays.include?(@date)
end
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter02/11-dependency-inversion-current-day-v4.rb | Ruby | mit | 206 | main | 309 | class CurrentDay
def initialize(date: Date.today,
schedule_class: MonthlySchedule)
@date = date
@schedule = schedule_class.new(date.year, date.month)
end
def work_hours
@schedule.work_hours_for(@date)
end
def workday?
!@schedule.holidays.include?(@date)
end
end |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter02/07-liskov-subsitution-max.rb | Ruby | mit | 206 | main | 440 | class Max
def initialize(max)
@max = max
end
def over?(n)
@max < n
end
end
class MaxBy < Max
def over?(n, by)
@max + by < n
end
end
class MaxBy < Max
def over?(n, by: 0)
@max + by < n
end
end
if obj.instance_of?(Max)
# do something
else
# do something else
end
if obj.class == Ma... |
github | PacktPublishing/Polished-Ruby-Programming | https://github.com/PacktPublishing/Polished-Ruby-Programming | Chapter02/13-html-table-v2.rb | Ruby | mit | 206 | main | 604 | class HTMLTable
class Element
def self.set_type(type)
define_method(:type){type}
end
def initialize(data)
@data = data
end
def to_s
"<#{type}>#{@data}</#{type}>"
end
end
%i"table tbody tr td".each do |type|
klass = Class.new(Element)
klass.set_type(type)
co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.