Skip to content

Instantly share code, notes, and snippets.

@peco8
Created September 11, 2016 11:14
Show Gist options
  • Save peco8/3904c18624bec978c1e13555d59b08b0 to your computer and use it in GitHub Desktop.
Save peco8/3904c18624bec978c1e13555d59b08b0 to your computer and use it in GitHub Desktop.
#1 Collecting input
# No input
def seconds_in_day
24 * 60 * 60
end
# This is the same as below
SECONDS_IN_DAY = 24 * 60 * 60
# With input, and it's most unambiguous
def seconds_in_days(num_days)
num_days * 24 * 60 * 60
end
# Input comes from Constant (Class or Module)
class TimeCalc
SECONDS_IN_DAY = 24 * 60 * 60
def seconds_in_days(num_days)
num_days * SECONDS_IN_DAY
end
end
# Input from another method
class TimeCalc
def seconds_in_week
seconds_in_days(7)
end
def seconds_in_days(num_days)
num_days * SECONDS_IN_DAY
end
end
# From instance varibles
class TimeCalc
def initialize
@start_date = Time.now # indirect input (like constant)
end
def time_n_days_from_now(num_days)
@start_date + num_days * 24 * 60 * 60
end
end
TimeCalc.new.time_n_days_from_now(2)
# The more indirect input comes, the more breakable the code is
def format_time
format = ENV.fetch('TIME_FORMAT'){ %D %r } # To get Ruby env object, and sending #fetch to that object.
Time.now.strftime(format)
end
format_time
# => "06/24/13 01:59:12 AM"
ENV['TIME_FORMAT'] = '%FT%T%:z'
format_time
# => "2013-06-24T01:59:12-04:00"
# Yaml fetch version
require 'yaml'
def format_time
prefs = YAML.load_file('time_pref.yml')
format = prefs.fetch( %D %r ) { Time.now.strftime(format)
end
IO.write('time-prefs.yml', <<EOF)
---
format: "%A, %B, %-d, at, %-I:%M %p"
EOF
format_time
# => "Monday, June 24 at 2:07 AM"
# More complicated
require 'yaml'
def format_time
user = ENV['USER']
prefs = YAML.load_file("/home/#{user}/time-prefs.yml")
format = prefs.fetch('format'){ '%D %r' }
Time.now.strftime(format)
end
# input-collection stanza.
require 'yaml'
def format_time
user = ENV['USER']
prefs = YAML.load_file("/home/#{user}/time-prefs.yml")
format = prefs.fetch('format'){ '%D %r' }
Time.now.strftime(format) # Let's emphasize this delineation with some added whitespace.
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment