Skip to content

Commit

Permalink
More code samples
Browse files Browse the repository at this point in the history
  • Loading branch information
practicingruby committed Feb 27, 2009
1 parent 1afc39a commit 7db25d4
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 3 deletions.
5 changes: 5 additions & 0 deletions when_things_go_wrong/foo.rb
@@ -0,0 +1,5 @@
begin
$ 5
rescue SyntaxError
nil
end
2 changes: 1 addition & 1 deletion when_things_go_wrong/report_bench.rb
Expand Up @@ -7,7 +7,7 @@

Benchmark.bmbm do |x|

x.report("inject-based to_html") do
x.report("inject based to_html") do
csv_data = CSV.read("report_data.csv")
r1 = ReportUnoptimized.new(csv_data)
r1.to_html
Expand Down
8 changes: 6 additions & 2 deletions when_things_go_wrong/server_logging.rb
Expand Up @@ -24,8 +24,12 @@ def /(x, y)

def handle_request(session)
action, *args = session.gets.split(/\s/)
@logger.info "executing: '#{action}' with #{args.inspect}"
session.puts(send(action, *args))
if ["*", "/"].include?(action)
@logger.info "executing: '#{action}' with #{args.inspect}"
session.puts(send(action, *args))
else
session.puts("Invalid command")
end
rescue StandardError => e
@logger.error(e.report)
session.puts "Sorry, something went wrong."
Expand Down
4 changes: 4 additions & 0 deletions worst_practices/kittens.txt
@@ -0,0 +1,4 @@
The kittens make me happy. They are hidden between the pages of this book,
secretly smiling at you while you read.

Wasn't that a great story?
58 changes: 58 additions & 0 deletions worst_practices/library.rb
@@ -0,0 +1,58 @@
module FattyRBP
class Formatter

def self.formats
@formats ||= {}
end

def self.format(name, options={}, &block)
formats[name] = Class.new(FattyRBP::Format, &block)
end

def self.render(format, options={})
formats[format].new(options).render
end
end

class Format
def initialize(options)
# not important
end
end
end


class Hello < FattyRBP::Formatter
format :text do
def render
"Hello World"
end
end

format :html do
def render
"<b>Hello World</b>"
end
end
end

puts Hello.render(:text)
puts Hello.render(:html)


class Goodbye < FattyRBP::Formatter
format :text do
def render
"Goodbye Cruel World!"
end
end
end

puts Goodbye.render(:text)


# Should not have changed
puts Hello.render(:text)

# Shouldn't exist
puts Goodbye.render(:html)
33 changes: 33 additions & 0 deletions worst_practices/user.rb
@@ -0,0 +1,33 @@
require "pstore"

class User

def self.data
@data ||= PStore.new("users.store")
end

def self.add(id, user_data)
data.transaction do
data[id] = user_data
end
end

def self.find(id)
data.transaction do
data[id] or raise "User not found"
end
end

def initialize(id)
@user_id = id
end

def attributes
self.class.find(@user_id)
end

def first_name
attributes[:first_name]
end

end

0 comments on commit 7db25d4

Please sign in to comment.