code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def set_error_in_env(env, e)
env["pliny.error"] = e
end
|
Sets the error in a predefined env key for use by the upstream
CanonicalLogLine middleware.
|
set_error_in_env
|
ruby
|
interagent/pliny
|
lib/pliny/middleware/rescue_errors.rb
|
https://github.com/interagent/pliny/blob/master/lib/pliny/middleware/rescue_errors.rb
|
MIT
|
def app
@rack_app || raise("Missing @rack_app")
end
|
the rack app to be tested with rack-test:
|
app
|
ruby
|
interagent/pliny
|
lib/template/spec/spec_helper.rb
|
https://github.com/interagent/pliny/blob/master/lib/template/spec/spec_helper.rb
|
MIT
|
def app
@rack_app || fail("Missing @rack_app")
end
|
the rack app to be tested with rack-test:
|
app
|
ruby
|
interagent/pliny
|
spec/spec_helper.rb
|
https://github.com/interagent/pliny/blob/master/spec/spec_helper.rb
|
MIT
|
def register_output_helper(method_name, mark_safe: false)
class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
# frozen_string_literal: true
def #{method_name}(*args, **kwargs, &block)
output = if block
view_context.#{method_name}(*args, **kwargs) { |*args| capture(*args, &block) }
else
view_context.#{method_name}(*args, **kwargs)
end
raw(#{mark_safe ? 'safe(output)' : 'output'})
end
RUBY
end
|
Register a Rails helper that returns safe HTML to be pushed to the output buffer.
|
register_output_helper
|
ruby
|
yippee-fun/phlex-rails
|
lib/phlex/rails/helper_macros.rb
|
https://github.com/yippee-fun/phlex-rails/blob/master/lib/phlex/rails/helper_macros.rb
|
MIT
|
def select_tag(name, *, **, &block)
output = if block
view_context.select_tag(name, capture(&block), *, **)
else
view_context.select_tag(name, *, **)
end
raw(output)
end
|
[Rails Docs](https://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag)
register_output_helper def select_tag(...) = nil
|
select_tag
|
ruby
|
yippee-fun/phlex-rails
|
lib/phlex/rails/helpers/select_tag.rb
|
https://github.com/yippee-fun/phlex-rails/blob/master/lib/phlex/rails/helpers/select_tag.rb
|
MIT
|
def tag(...)
result = view_context.tag(...)
case result
when ActiveSupport::SafeBuffer
raw(result)
when ActionView::Helpers::TagHelper::TagBuilder
Phlex::Rails::Buffered.new(
result,
component: self,
)
end
end
|
[Rails Docs](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag)
|
tag
|
ruby
|
yippee-fun/phlex-rails
|
lib/phlex/rails/helpers/tag.rb
|
https://github.com/yippee-fun/phlex-rails/blob/master/lib/phlex/rails/helpers/tag.rb
|
MIT
|
def translate(key, **)
key = "#{self.class.translation_path}#{key}" if key.start_with?(".")
view_context.t(key, **)
end
|
[Rails Docs](https://api.rubyonrails.org/classes/AbstractController/Translation.html#method-i-translate)
|
translate
|
ruby
|
yippee-fun/phlex-rails
|
lib/phlex/rails/helpers/translate.rb
|
https://github.com/yippee-fun/phlex-rails/blob/master/lib/phlex/rails/helpers/translate.rb
|
MIT
|
def turbo_stream(...)
Phlex::Rails::Buffered.new(
view_context.turbo_stream(...),
component: self,
)
end
|
[Turbo Docs](https://rubydoc.info/github/hotwired/turbo-rails/Turbo/StreamsHelper#turbo_stream-instance_method)
|
turbo_stream
|
ruby
|
yippee-fun/phlex-rails
|
lib/phlex/rails/helpers/turbo_stream.rb
|
https://github.com/yippee-fun/phlex-rails/blob/master/lib/phlex/rails/helpers/turbo_stream.rb
|
MIT
|
def pygmentize?
@_pygmentize ||= ENV['PATH'].split(':').
any? { |dir| File.executable?("#{dir}/pygmentize") }
end
|
Helper Functions
----------------
Returns `true` if `pygmentize` is available locally, `false` otherwise.
|
pygmentize?
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def detect_language
@_language ||=
if pygmentize?
%x[pygmentize -N #{@file}].strip.split('+').first
else
"text"
end
end
|
If `pygmentize` is available, we can use it to autodetect a file's
language based on its filename. Filenames without extensions, or with
extensions that `pygmentize` doesn't understand will return `text`.
We'll also return `text` if `pygmentize` isn't available.
We'll memoize the result, as we'll call this a few times.
|
detect_language
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def parse(data)
sections, docs, code = [], [], []
lines = data.split("\n")
# The first line is ignored if it is a shebang line. We also ignore the
# PEP 263 encoding information in python sourcefiles, and the similar ruby
# 1.9 syntax.
lines.shift if lines[0] =~ /^\#\!/
lines.shift if lines[0] =~ /coding[:=]\s*[-\w.]+/ &&
[ "python", "rb" ].include?(@options[:language])
# To detect both block comments and single-line comments, we'll set
# up a tiny state machine, and loop through each line of the file.
# This requires an `in_comment_block` boolean, and a few regular
# expressions for line tests. We'll do the same for fake heredoc parsing.
in_comment_block = false
in_heredoc = false
single_line_comment, block_comment_start, block_comment_mid, block_comment_end =
nil, nil, nil, nil
if not @options[:comment_chars][:single].nil?
single_line_comment = Regexp.new("^\\s*#{Regexp.escape(@options[:comment_chars][:single])}\\s?")
end
if not @options[:comment_chars][:multi].nil?
block_comment_start = Regexp.new("^\\s*#{Regexp.escape(@options[:comment_chars][:multi][:start])}\\s*$")
block_comment_end = Regexp.new("^\\s*#{Regexp.escape(@options[:comment_chars][:multi][:end])}\\s*$")
block_comment_one_liner = Regexp.new("^\\s*#{Regexp.escape(@options[:comment_chars][:multi][:start])}\\s*(.*?)\\s*#{Regexp.escape(@options[:comment_chars][:multi][:end])}\\s*$")
block_comment_start_with = Regexp.new("^\\s*#{Regexp.escape(@options[:comment_chars][:multi][:start])}\\s*(.*?)$")
block_comment_end_with = Regexp.new("\\s*(.*?)\\s*#{Regexp.escape(@options[:comment_chars][:multi][:end])}\\s*$")
if @options[:comment_chars][:multi][:middle]
block_comment_mid = Regexp.new("^\\s*#{Regexp.escape(@options[:comment_chars][:multi][:middle])}\\s?")
end
end
if not @options[:comment_chars][:heredoc].nil?
heredoc_start = Regexp.new("#{Regexp.escape(@options[:comment_chars][:heredoc])}(\\S+)$")
end
lines.each do |line|
# If we're currently in a comment block, check whether the line matches
# the _end_ of a comment block or the _end_ of a comment block with a
# comment.
if in_comment_block
if block_comment_end && line.match(block_comment_end)
in_comment_block = false
elsif block_comment_end_with && line.match(block_comment_end_with)
in_comment_block = false
docs << line.match(block_comment_end_with).captures.first.
sub(block_comment_mid || '', '')
else
docs << line.sub(block_comment_mid || '', '')
end
# If we're currently in a heredoc, we're looking for the end of the
# heredoc, and everything it contains is code.
elsif in_heredoc
if line.match(Regexp.new("^#{Regexp.escape(in_heredoc)}$"))
in_heredoc = false
end
code << line
# Otherwise, check whether the line starts a heredoc. If so, note the end
# pattern, and the line is code. Otherwise check whether the line matches
# the beginning of a block, or a single-line comment all on it's lonesome.
# In either case, if there's code, start a new section.
else
if heredoc_start && line.match(heredoc_start)
in_heredoc = $1
code << line
elsif block_comment_one_liner && line.match(block_comment_one_liner)
if code.any?
sections << [docs, code]
docs, code = [], []
end
docs << line.match(block_comment_one_liner).captures.first
elsif block_comment_start && line.match(block_comment_start)
in_comment_block = true
if code.any?
sections << [docs, code]
docs, code = [], []
end
elsif block_comment_start_with && line.match(block_comment_start_with)
in_comment_block = true
if code.any?
sections << [docs, code]
docs, code = [], []
end
docs << line.match(block_comment_start_with).captures.first
elsif single_line_comment && line.match(single_line_comment)
if code.any?
sections << [docs, code]
docs, code = [], []
end
docs << line.sub(single_line_comment || '', '')
else
code << line
end
end
end
sections << [docs, code] if docs.any? || code.any?
normalize_leading_spaces(sections)
end
|
Internal Parsing and Highlighting
---------------------------------
Parse the raw file data into a list of two-tuples. Each tuple has the
form `[docs, code]` where both elements are arrays containing the
raw lines parsed from the input file, comment characters stripped.
|
parse
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def normalize_leading_spaces(sections)
sections.map do |section|
if section.any? && section[0].any?
leading_space = section[0][0].match("^\s+")
if leading_space
section[0] =
section[0].map{ |line| line.sub(/^#{leading_space.to_s}/, '') }
end
end
section
end
end
|
Normalizes documentation whitespace by checking for leading whitespace,
removing it, and then removing the same amount of whitespace from each
succeeding line. That is:
def func():
"""
Comment 1
Comment 2
"""
print "omg!"
should yield a comment block of `Comment 1\nComment 2` and code of
`def func():\n print "omg!"`
|
normalize_leading_spaces
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def split(sections)
docs_blocks, code_blocks = [], []
sections.each do |docs,code|
docs_blocks << docs.join("\n")
code_blocks << code.map do |line|
tabs = line.match(/^(\t+)/)
tabs ? line.sub(/^\t+/, ' ' * tabs.captures[0].length) : line
end.join("\n")
end
[docs_blocks, code_blocks]
end
|
Take the list of paired *sections* two-tuples and split into two
separate lists: one holding the comments with leaders removed and
one with the code blocks.
|
split
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def docblock(docs)
docs.map do |doc|
doc.split("\n").map do |line|
line.match(/^@\w+/) ? line.sub(/^@(\w+)\s+/, '> **\1** ')+" " : line
end.join("\n")
end
end
|
Take a list of block comments and convert Docblock @annotations to
Markdown syntax.
|
docblock
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def highlight(blocks)
docs_blocks, code_blocks = blocks
# Pre-process Docblock @annotations.
docs_blocks = docblock(docs_blocks) if @options[:docblocks]
# Combine all docs blocks into a single big markdown document with section
# dividers and run through the Markdown processor. Then split it back out
# into separate sections.
markdown = docs_blocks.join("\n\n##### DIVIDER\n\n")
docs_html = process_markdown(markdown).split(/\n*<h5>DIVIDER<\/h5>\n*/m)
# Combine all code blocks into a single big stream with section dividers and
# run through either `pygmentize(1)` or <http://pygments.appspot.com>
span, espan = '<span class="c.?">', '</span>'
if @options[:comment_chars][:single]
front = @options[:comment_chars][:single]
divider_input = "\n\n#{front} DIVIDER\n\n"
divider_output = Regexp.new(
[ "\\n*",
span,
Regexp.escape(CGI.escapeHTML(front)),
' DIVIDER',
espan,
"\\n*"
].join, Regexp::MULTILINE
)
else
front = @options[:comment_chars][:multi][:start]
back = @options[:comment_chars][:multi][:end]
divider_input = "\n\n#{front}\nDIVIDER\n#{back}\n\n"
divider_output = Regexp.new(
[ "\\n*",
span, Regexp.escape(CGI.escapeHTML(front)), espan,
"\\n",
span, "DIVIDER", espan,
"\\n",
span, Regexp.escape(CGI.escapeHTML(back)), espan,
"\\n*"
].join, Regexp::MULTILINE
)
end
code_stream = code_blocks.join(divider_input)
code_html =
if pygmentize?
highlight_pygmentize(code_stream)
else
highlight_webservice(code_stream)
end
# Do some post-processing on the pygments output to split things back
# into sections and remove partial `<pre>` blocks.
code_html = code_html.
split(divider_output).
map { |code| code.sub(/\n?<div class="highlight"><pre>/m, '') }.
map { |code| code.sub(/\n?<\/pre><\/div>\n/m, '') }
# Lastly, combine the docs and code lists back into a list of two-tuples.
docs_html.zip(code_html)
end
|
Take the result of `split` and apply Markdown formatting to comments and
syntax highlighting to source code.
|
highlight
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def highlight_pygmentize(code)
code_html = nil
open("|pygmentize -l #{@options[:language]} -O encoding=utf-8 -f html", 'r+') do |fd|
pid =
fork {
fd.close_read
fd.write code
fd.close_write
exit!
}
fd.close_write
code_html = fd.read
fd.close_read
Process.wait(pid)
end
code_html
end
|
We `popen` a read/write pygmentize process in the parent and
then fork off a child process to write the input.
|
highlight_pygmentize
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def highlight_webservice(code)
url = URI.parse 'http://pygments.appspot.com/'
options = { 'lang' => @options[:language], 'code' => code}
Net::HTTP.post_form(url, options).body
end
|
Pygments is not one of those things that's trivial for a ruby user to install,
so we'll fall back on a webservice to highlight the code if it isn't available.
|
highlight_webservice
|
ruby
|
rtomayko/rocco
|
lib/rocco.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco.rb
|
MIT
|
def define_directory_task(path)
directory path
task @name => path
end
|
Define the destination directory task and make the `:rocco` task depend
on it. This causes the destination directory to be created if it doesn't
already exist.
|
define_directory_task
|
ruby
|
rtomayko/rocco
|
lib/rocco/tasks.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco/tasks.rb
|
MIT
|
def define_file_task(source_file, dest_file)
prerequisites = [@dest, source_file] + rocco_source_files
file dest_file => prerequisites do |f|
verbose { puts "rocco: #{source_file} -> #{dest_file}" }
rocco = Rocco.new(source_file, @sources.to_a, @options)
FileUtils.mkdir_p(File.dirname(dest_file))
File.open(dest_file, 'wb') { |fd| fd.write(rocco.to_html) }
end
task @name => dest_file
end
|
Setup a `file` task for a single Rocco output file (`dest_file`). It
depends on the source file, the destination directory, and all of Rocco's
internal source code, so that the destination file is rebuilt when any of
those changes.
You can run these tasks directly with Rake:
rake docs/foo.html docs/bar.html
... would generate the `foo.html` and `bar.html` files but only if they
don't already exist or one of their dependencies was changed.
|
define_file_task
|
ruby
|
rtomayko/rocco
|
lib/rocco/tasks.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco/tasks.rb
|
MIT
|
def rocco_source_files
libdir = File.expand_path('../..', __FILE__)
FileList["#{libdir}/rocco.rb", "#{libdir}/rocco/**"]
end
|
Return a `FileList` that includes all of Roccos source files. This causes
output files to be regenerated properly when someone upgrades the Rocco
library.
|
rocco_source_files
|
ruby
|
rtomayko/rocco
|
lib/rocco/tasks.rb
|
https://github.com/rtomayko/rocco/blob/master/lib/rocco/tasks.rb
|
MIT
|
def connection(options={})
raise NoToken if @token.to_s.empty?
@connections ||= {}
cached_connection? && !protocol_changed? ? cached_connection : new_connection
end
|
this is your connection for the entire module
|
connection
|
ruby
|
jsmestad/pivotal-tracker
|
lib/pivotal-tracker/client.rb
|
https://github.com/jsmestad/pivotal-tracker/blob/master/lib/pivotal-tracker/client.rb
|
MIT
|
def initialize *a, &b
@version = nil
@leftovers = []
@specs = {}
@long = {}
@short = {}
@order = []
@constraints = []
@stop_words = []
@stop_on_unknown = false
#instance_eval(&b) if b # can't take arguments
cloaker(&b).bind(self).call(*a) if b
end
|
# Initializes the parser, and instance-evaluates any block given.
|
initialize
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def opt name, desc="", opts={}
raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
## fill in :type
opts[:type] = # normalize
case opts[:type]
when :boolean, :bool; :flag
when :integer; :int
when :integers; :ints
when :double; :float
when :doubles; :floats
when Class
case opts[:type].name
when 'TrueClass', 'FalseClass'; :flag
when 'String'; :string
when 'Integer'; :int
when 'Float'; :float
when 'IO'; :io
when 'Date'; :date
else
raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
end
when nil; nil
else
raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
opts[:type]
end
## for options with :multi => true, an array default doesn't imply
## a multi-valued argument. for that you have to specify a :type
## as well. (this is how we disambiguate an ambiguous situation;
## see the docs for Parser#opt for details.)
disambiguated_default = if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
opts[:default].first
else
opts[:default]
end
type_from_default =
case disambiguated_default
when Integer; :int
when Numeric; :float
when TrueClass, FalseClass; :flag
when String; :string
when IO; :io
when Date; :date
when Array
if opts[:default].empty?
raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
end
case opts[:default][0] # the first element determines the types
when Integer; :ints
when Numeric; :floats
when String; :strings
when IO; :ios
when Date; :dates
else
raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
end
when nil; nil
else
raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
end
raise ArgumentError, ":type specification and default type don't match (default type is #{type_from_default})" if opts[:type] && type_from_default && opts[:type] != type_from_default
opts[:type] = opts[:type] || type_from_default || :flag
## fill in :long
opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-")
opts[:long] = case opts[:long]
when /^--([^-].*)$/; $1
when /^[^-]/; opts[:long]
else; raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
end
raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
## fill in :short
opts[:short] = opts[:short].to_s if opts[:short] unless opts[:short] == :none
opts[:short] = case opts[:short]
when /^-(.)$/; $1
when nil, :none, /^.$/; opts[:short]
else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
end
if opts[:short]
raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
end
## fill in :default for flags
opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
## autobox :default for :multi (multi-occurrence) arguments
opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
## fill in :multi
opts[:multi] ||= false
opts[:desc] ||= desc
@long[opts[:long]] = name
@short[opts[:short]] = name if opts[:short] && opts[:short] != :none
@specs[name] = opts
@order << [:opt, name]
end
|
# Define an option. +name+ is the option name, a unique identifier
# for the option that you will use internally, which should be a
# symbol or a string. +desc+ is a string description which will be
# displayed in help messages.
#
# Takes the following optional arguments:
#
# [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
# [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
# [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
# [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
# [+:required+] If set to +true+, the argument must be provided on the commandline.
# [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
#
# Note that there are two types of argument multiplicity: an argument
# can take multiple values, e.g. "--arg 1 2 3". An argument can also
# be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
#
# Arguments that take multiple values should have a +:type+ parameter
# drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
# value of an array of the correct type (e.g. [String]). The
# value of this argument will be an array of the parameters on the
# commandline.
#
# Arguments that can occur multiple times should be marked with
# +:multi+ => +true+. The value of this argument will also be an array.
# In contrast with regular non-multi options, if not specified on
# the commandline, the default value will be [], not nil.
#
# These two attributes can be combined (e.g. +:type+ => +:strings+,
# +:multi+ => +true+), in which case the value of the argument will be
# an array of arrays.
#
# There's one ambiguous case to be aware of: when +:multi+: is true and a
# +:default+ is set to an array (of something), it's ambiguous whether this
# is a multi-value argument as well as a multi-occurrence argument.
# In thise case, Trollop assumes that it's not a multi-value argument.
# If you want a multi-value, multi-occurrence argument with a default
# value, you must specify +:type+ as well.
|
opt
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def depends *syms
syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
@constraints << [:depends, syms]
end
|
# Marks two (or more!) options as requiring each other. Only handles
# undirected (i.e., mutual) dependencies. Directed dependencies are
# better modeled with Trollop::die.
|
depends
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def conflicts *syms
syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
@constraints << [:conflicts, syms]
end
|
# Marks two (or more!) options as conflicting.
|
conflicts
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def stop_on *words
@stop_words = [*words].flatten
end
|
# Defines a set of words which cause parsing to terminate when
# encountered, such that any options to the left of the word are
# parsed as usual, and options to the right of the word are left
# intact.
#
# A typical use case would be for subcommand support, where these
# would be set to the list of subcommands. A subsequent Trollop
# invocation would then be used to parse subcommand options, after
# shifting the subcommand off of ARGV.
|
stop_on
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def stop_on_unknown
@stop_on_unknown = true
end
|
# Similar to #stop_on, but stops on any unknown word when encountered
# (unless it is a parameter for an argument). This is useful for
# cases where you don't know the set of subcommands ahead of time,
# i.e., without first parsing the global options.
|
stop_on_unknown
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def parse cmdline=ARGV
vals = {}
required = {}
opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
opt :help, "Show this message" unless @specs[:help] || @long["help"]
@specs.each do |sym, opts|
required[sym] = true if opts[:required]
vals[sym] = opts[:default]
vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
end
resolve_default_short_options!
## resolve symbols
given_args = {}
@leftovers = each_arg cmdline do |arg, params|
## handle --no- forms
arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
["--#{$1}", true]
else
[arg, false]
end
sym = case arg
when /^-([^-])$/; @short[$1]
when /^--([^-]\S*)$/; @long[$1] || @long["no-#{$1}"]
else; raise CommandlineError, "invalid argument syntax: '#{arg}'"
end
sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments
raise CommandlineError, "unknown argument '#{arg}'" unless sym
if given_args.include?(sym) && !@specs[sym][:multi]
raise CommandlineError, "option '#{arg}' specified multiple times"
end
given_args[sym] ||= {}
given_args[sym][:arg] = arg
given_args[sym][:negative_given] = negative_given
given_args[sym][:params] ||= []
# The block returns the number of parameters taken.
num_params_taken = 0
unless params.nil?
if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params[0, 1] # take the first parameter
num_params_taken = 1
elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params # take all the parameters
num_params_taken = params.size
end
end
num_params_taken
end
## check for version and help args
raise VersionNeeded if given_args.include? :version
raise HelpNeeded if given_args.include? :help
## check constraint satisfaction
@constraints.each do |type, syms|
constraint_sym = syms.find { |sym| given_args[sym] }
next unless constraint_sym
case type
when :depends
syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
when :conflicts
syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
end
end
required.each do |sym, val|
raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
end
## parse parameters
given_args.each do |sym, given_data|
arg, params, negative_given = given_data.values_at :arg, :params, :negative_given
opts = @specs[sym]
raise CommandlineError, "option '#{arg}' needs a parameter" if params.empty? && opts[:type] != :flag
vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
case opts[:type]
when :flag
vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
when :int, :ints
vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
when :float, :floats
vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
when :string, :strings
vals[sym] = params.map { |pg| pg.map { |p| p.to_s } }
when :io, :ios
vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
when :date, :dates
vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
end
if SINGLE_ARG_TYPES.include?(opts[:type])
unless opts[:multi] # single parameter
vals[sym] = vals[sym][0][0]
else # multiple options, each with a single parameter
vals[sym] = vals[sym].map { |p| p[0] }
end
elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
vals[sym] = vals[sym][0] # single option, with multiple parameters
end
# else: multiple options, with multiple parameters
end
## modify input in place with only those
## arguments we didn't process
cmdline.clear
@leftovers.each { |l| cmdline << l }
## allow openstruct-style accessors
class << vals
def method_missing(m, *args)
self[m] || self[m.to_s]
end
end
vals
end
|
# Parses the commandline. Typically called by Trollop::options,
# but you can call it directly if you need more control.
#
# throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
|
parse
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def educate stream=$stdout
width # hack: calculate it now; otherwise we have to be careful not to
# call this unless the cursor's at the beginning of a line.
left = {}
@specs.each do |name, spec|
left[name] = "--#{spec[:long]}" +
(spec[:type] == :flag && spec[:default] ? ", --no-#{spec[:long]}" : "") +
(spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
case spec[:type]
when :flag; ""
when :int; " <i>"
when :ints; " <i+>"
when :string; " <s>"
when :strings; " <s+>"
when :float; " <f>"
when :floats; " <f+>"
when :io; " <filename/uri>"
when :ios; " <filename/uri+>"
when :date; " <date>"
when :dates; " <date+>"
end
end
leftcol_width = left.values.map { |s| s.length }.max || 0
rightcol_start = leftcol_width + 6 # spaces
unless @order.size > 0 && @order.first.first == :text
stream.puts "#@version\n" if @version
stream.puts "Options:"
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %#{leftcol_width}s: ", left[opt]
desc = spec[:desc] + begin
default_s = case spec[:default]
when $stdout; "<stdout>"
when $stdin; "<stdin>"
when $stderr; "<stderr>"
when Array
spec[:default].join(", ")
else
spec[:default].to_s
end
if spec[:default]
if spec[:desc] =~ /\.$/
" (Default: #{default_s})"
else
" (default: #{default_s})"
end
else
""
end
end
stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
end
end
|
# Print the help message to +stream+.
|
educate
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def die arg, msg
if msg
$stderr.puts "Error: argument --#{@specs[arg][:long]} #{msg}."
else
$stderr.puts "Error: #{arg}."
end
$stderr.puts "Try --help for help."
exit(-1)
end
|
# The per-parser version of Trollop::die (see that for documentation).
|
die
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def cloaker &b
(class << self; self; end).class_eval do
define_method :cloaker_, &b
meth = instance_method :cloaker_
remove_method :cloaker_
meth
end
end
|
# instance_eval but with ability to handle block arguments
# thanks to _why: http://redhanded.hobix.com/inspect/aBlockCostume.html
|
cloaker
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def options args=ARGV, *a, &b
@last_parser = Parser.new(*a, &b)
with_standard_exception_handling(@last_parser) { @last_parser.parse args }
end
|
# The easy, syntactic-sugary entry method into Trollop. Creates a Parser,
# passes the block to it, then parses +args+ with it, handling any errors or
# requests for help or version information appropriately (and then exiting).
# Modifies +args+ in place. Returns a hash of option values.
#
# The block passed in should contain zero or more calls to +opt+
# (Parser#opt), zero or more calls to +text+ (Parser#text), and
# probably a call to +version+ (Parser#version).
#
# The returned block contains a value for every option specified with
# +opt+. The value will be the value given on the commandline, or the
# default value if the option was not specified on the commandline. For
# every option specified on the commandline, a key "<option
# name>_given" will also be set in the hash.
#
# Example:
#
# require 'trollop'
# opts = Trollop::options do
# opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
# opt :name, "Monkey name", :type => :string # a string --name <s>, defaulting to nil
# opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
# end
#
# ## if called with no arguments
# p opts # => {:monkey=>false, :name=>nil, :num_limbs=>4, :help=>false}
#
# ## if called with --monkey
# p opts # => {:monkey=>true, :name=>nil, :num_limbs=>4, :help=>false, :monkey_given=>true}
#
# See more examples at http://trollop.rubyforge.org.
|
options
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def with_standard_exception_handling parser
begin
yield
rescue CommandlineError => e
$stderr.puts "Error: #{e.message}."
$stderr.puts "Try --help for help."
exit(-1)
rescue HelpNeeded
parser.educate
exit
rescue VersionNeeded
puts parser.version
exit
end
end
|
# If Trollop::options doesn't do quite what you want, you can create a Parser
# object and call Parser#parse on it. That method will throw CommandlineError,
# HelpNeeded and VersionNeeded exceptions when necessary; if you want to
# have these handled for you in the standard manner (e.g. show the help
# and then exit upon an HelpNeeded exception), call your code from within
# a block passed to this method.
#
# Note that this method will call System#exit after handling an exception!
#
# Usage example:
#
# require 'trollop'
# p = Trollop::Parser.new do
# opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
# opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
# end
#
# opts = Trollop::with_standard_exception_handling p do
# o = p.parse ARGV
# raise Trollop::HelpNeeded if ARGV.empty? # show help screen
# o
# end
#
# Requires passing in the parser object.
|
with_standard_exception_handling
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def die arg, msg=nil
if @last_parser
@last_parser.die arg, msg
else
raise ArgumentError, "Trollop::die can only be called after Trollop::options"
end
end
|
# Informs the user that their usage of 'arg' was wrong, as detailed by
# 'msg', and dies. Example:
#
# options do
# opt :volume, :default => 0.0
# end
#
# die :volume, "too loud" if opts[:volume] > 10.0
# die :volume, "too soft" if opts[:volume] < 0.1
#
# In the one-argument case, simply print that message, a notice
# about -h, and die. Example:
#
# options do
# opt :whatever # ...
# end
#
# Trollop::die "need at least one filename" if ARGV.empty?
|
die
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/trollop.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/trollop.rb
|
MIT
|
def blank_value?(hash, key)
if hash.key?(key)
value = hash[key]
return true if value.nil? || "" == value
end
false
end
|
Checks if setting a blank value
returns true if the key is included in the hash
and its value is empty or nil
|
blank_value?
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/stripe_mock/request_handlers/accounts.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/stripe_mock/request_handlers/accounts.rb
|
MIT
|
def invoice_charge(invoice)
begin
new_charge(nil, nil, {customer: invoice[:customer]["id"], amount: invoice[:amount_due], currency: StripeMock.default_currency}, nil)
rescue Stripe::InvalidRequestError
new_charge(nil, nil, {source: generate_card_token, amount: invoice[:amount_due], currency: StripeMock.default_currency}, nil)
end
end
|
# charge the customer on the invoice, if one does not exist, create
anonymous charge
|
invoice_charge
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/stripe_mock/request_handlers/invoices.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/stripe_mock/request_handlers/invoices.rb
|
MIT
|
def get_payment_method(route, method_url, params, headers)
id = method_url.match(route)[1] || params[:payment_method]
payment_method = assert_existence :payment_method, id, payment_methods[id]
payment_method.clone
end
|
params: {:type=>"card", :customer=>"test_cus_3"}
get /v1/payment_methods/:id
|
get_payment_method
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/stripe_mock/request_handlers/payment_methods.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/stripe_mock/request_handlers/payment_methods.rb
|
MIT
|
def verify_card_present(customer, plan, subscription, params={})
return if customer[:default_source]
return if customer[:invoice_settings][:default_payment_method]
return if customer[:trial_end]
return if params[:trial_end]
return if params[:payment_behavior] == 'default_incomplete'
return if subscription[:default_payment_method]
plan_trial_period_days = plan[:trial_period_days] || 0
plan_has_trial = plan_trial_period_days != 0 || plan[:amount] == 0 || plan[:trial_end]
return if plan && plan_has_trial
return if subscription && subscription[:trial_end] && subscription[:trial_end] != 'now'
if subscription[:items]
trial = subscription[:items][:data].none? do |item|
plan = item[:plan]
(plan[:trial_period_days].nil? || plan[:trial_period_days] == 0) &&
(plan[:trial_end].nil? || plan[:trial_end] == 'now')
end
return if trial
end
return if params[:billing] == 'send_invoice'
raise Stripe::InvalidRequestError.new('This customer has no attached payment source', nil, http_status: 400)
end
|
Ensure customer has card to charge unless one of the following criterias is met:
1) is in trial
2) is free
3) has billing set to send invoice
|
verify_card_present
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/stripe_mock/request_handlers/subscriptions.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/stripe_mock/request_handlers/subscriptions.rb
|
MIT
|
def get_ending_time(start_time, plan, intervals = 1)
return start_time unless plan
interval = plan[:interval] || plan.dig(:recurring, :interval)
interval_count = plan[:interval_count] || plan.dig(:recurring, :interval_count) || 1
case interval
when "week"
start_time + (604800 * (interval_count) * intervals)
when "month"
(Time.at(start_time).to_datetime >> ((interval_count) * intervals)).to_time.to_i
when "year"
(Time.at(start_time).to_datetime >> (12 * intervals)).to_time.to_i # max period is 1 year
else
start_time
end
end
|
`intervals` is set to 1 when calculating current_period_end from current_period_start & plan
`intervals` is set to 2 when calculating Stripe::Invoice.upcoming end from current_period_start & plan
|
get_ending_time
|
ruby
|
stripe-ruby-mock/stripe-ruby-mock
|
lib/stripe_mock/request_handlers/helpers/subscription_helpers.rb
|
https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/stripe_mock/request_handlers/helpers/subscription_helpers.rb
|
MIT
|
def test_no_save_after_destroy
paranoid = ParanoidString.first
paranoid.destroy
paranoid.name = "Let's update!"
assert_not paranoid.save
assert_raises ActiveRecord::RecordNotSaved do
paranoid.save!
end
end
|
Rails does not allow saving deleted records
|
test_no_save_after_destroy
|
ruby
|
ActsAsParanoid/acts_as_paranoid
|
test/legacy/core_test.rb
|
https://github.com/ActsAsParanoid/acts_as_paranoid/blob/master/test/legacy/core_test.rb
|
MIT
|
def test_string_type_with_no_nil_value_before_destroy
ps = ParanoidString.create!(deleted: "not dead")
assert_equal 1, ParanoidString.where(id: ps).count
end
|
Test string type columns that don't have a nil value when not deleted (Y/N for example)
|
test_string_type_with_no_nil_value_before_destroy
|
ruby
|
ActsAsParanoid/acts_as_paranoid
|
test/legacy/core_test.rb
|
https://github.com/ActsAsParanoid/acts_as_paranoid/blob/master/test/legacy/core_test.rb
|
MIT
|
def test_boolean_type_with_no_nil_value_before_destroy
ps = ParanoidBooleanNotNullable.create!
assert_equal 1, ParanoidBooleanNotNullable.where(id: ps).count
end
|
Test boolean type columns, that are not nullable
|
test_boolean_type_with_no_nil_value_before_destroy
|
ruby
|
ActsAsParanoid/acts_as_paranoid
|
test/legacy/core_test.rb
|
https://github.com/ActsAsParanoid/acts_as_paranoid/blob/master/test/legacy/core_test.rb
|
MIT
|
def convert_booleans(hash)
hash.each_pair.with_object({}, &method(:convert_boolean))
end
|
Convert each boolean in the hash to integer
if it is a boolean field
@param hash [Hash]
@return [Hash]
|
convert_booleans
|
ruby
|
tpitale/staccato
|
lib/staccato/boolean_helpers.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/boolean_helpers.rb
|
MIT
|
def convert_boolean((k,v), hash)
hash[k] = boolean_field?(k) ? integer_for(v) : v
end
|
Method to convert a single field from bool to int
@param hash [#[]=] the collector object
|
convert_boolean
|
ruby
|
tpitale/staccato
|
lib/staccato/boolean_helpers.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/boolean_helpers.rb
|
MIT
|
def integer_for(value)
case value
when Integer
value
when TrueClass
1
when FalseClass
0
when NilClass
nil
end
end
|
Convert a value to appropriate int
@param value [nil, true, false, Integer]
@return [nil, Integer]
|
integer_for
|
ruby
|
tpitale/staccato
|
lib/staccato/boolean_helpers.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/boolean_helpers.rb
|
MIT
|
def boolean_fields
super + [:fatal]
end
|
Boolean fields from Hit plus exception-specific field
@return [Array<Symbol>]
|
boolean_fields
|
ruby
|
tpitale/staccato
|
lib/staccato/exception.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/exception.rb
|
MIT
|
def initialize(tracker, options = {})
self.tracker = tracker
self.options = OptionSet.new(convert_booleans(options))
end
|
sets up a new hit
@param tracker [Staccato::Tracker] the tracker to collect to
@param options [Hash] options for the specific hit type
|
initialize
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def params
{}
.merge!(base_params)
.merge!(tracker_default_params)
.merge!(global_options_params)
.merge!(hit_params)
.merge!(custom_dimensions)
.merge!(custom_metrics)
.merge!(measurement_params)
.reject {|_,v| v.nil?}
end
|
collects the parameters from options for this hit type
|
params
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def add_custom_dimension(index, value)
self.custom_dimensions["cd#{index}"] = value
end
|
Set a custom dimension value at an index
@param index [Integer]
@param value
|
add_custom_dimension
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def custom_dimensions
@custom_dimensions ||= {}
end
|
Custom dimensions for this hit
@return [Hash]
|
custom_dimensions
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def add_custom_metric(index, value)
self.custom_metrics["cm#{index}"] = value
end
|
Set a custom metric value at an index
@param index [Integer]
@param value
|
add_custom_metric
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def custom_metrics
@custom_metrics ||= {}
end
|
Custom metrics for this hit
@return [Hash]
|
custom_metrics
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def add_measurement(key, options = {})
if options.is_a?(Hash)
self.measurements << Measurement.lookup(key).new(options)
else
self.measurements << options
end
end
|
Add a measurement by its symbol name with options
@param key [Symbol] any one of the measurable classes lookup key
@param options [Hash or Object] for the measurement
|
add_measurement
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def measurements
@measurements ||= []
end
|
Measurements for this hit
@return [Array<Measurable>]
|
measurements
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def session_control
case
when options[:session_start], options[:start_session]
'start'
when options[:session_end], options[:end_session], options[:stop_session]
'end'
end
end
|
Returns the value for session control
based on options for session_start/_end
@return ['start', 'end']
|
session_control
|
ruby
|
tpitale/staccato
|
lib/staccato/hit.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/hit.rb
|
MIT
|
def initialize(options = {})
self.options = OptionSet.new(options)
validate_options
end
|
@param options [Hash] options for the measurement fields
|
initialize
|
ruby
|
tpitale/staccato
|
lib/staccato/measurable.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurable.rb
|
MIT
|
def params
{}
.merge!(measurable_params)
.merge!(custom_dimensions)
.merge!(custom_metrics)
.reject {|_,v| v.nil?}
end
|
collects the parameters from options for this measurement
@return [Hash]
|
params
|
ruby
|
tpitale/staccato
|
lib/staccato/measurable.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurable.rb
|
MIT
|
def add_custom_dimension(dimension_index, value)
return unless custom_fields_allowed?
self.custom_dimensions["#{prefix}cd#{dimension_index}"] = value
end
|
Set a custom dimension value at an index
@param dimension_index [Integer]
@param value
|
add_custom_dimension
|
ruby
|
tpitale/staccato
|
lib/staccato/measurable.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurable.rb
|
MIT
|
def custom_dimensions
@custom_dimensions ||= {}
end
|
Custom dimensions for this measurable
@return [Hash]
|
custom_dimensions
|
ruby
|
tpitale/staccato
|
lib/staccato/measurable.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurable.rb
|
MIT
|
def add_custom_metric(metric_index, value)
return unless custom_fields_allowed?
self.custom_metrics["#{prefix}cm#{metric_index}"] = value
end
|
Set a custom metric value at an index
@param metric_index [Integer]
@param value
|
add_custom_metric
|
ruby
|
tpitale/staccato
|
lib/staccato/measurable.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurable.rb
|
MIT
|
def custom_metrics
@custom_metrics ||= {}
end
|
Custom metrics for this measurable
@return [Hash]
|
custom_metrics
|
ruby
|
tpitale/staccato
|
lib/staccato/measurable.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurable.rb
|
MIT
|
def lookup(key)
measurement_types[key] || NullMeasurement
end
|
Lookup a measurement class by its key
@param key [Symbol]
@return [Class] measurement class or NullMeasurement
|
lookup
|
ruby
|
tpitale/staccato
|
lib/staccato/measurement.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/measurement.rb
|
MIT
|
def track!(&block)
if block_given?
start_at = Time.now
block.call
end_at = Time.now
self.options.time = (end_at - start_at).to_i*1000
end
super
end
|
tracks the timing hit type
@param block [#call] block is executed and time recorded
|
track!
|
ruby
|
tpitale/staccato
|
lib/staccato/timing.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/timing.rb
|
MIT
|
def initialize(id, client_id = nil, options = {})
@id = id
@client_id = client_id
@ssl = options.delete(:ssl) || false
@adapters = []
self.hit_defaults = options
end
|
sets up a new tracker
@param id [String] the GA tracker id
@param client_id [String, nil] unique value to track user sessions
@param hit_defaults [Hash]
|
initialize
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def client_id
@client_id ||= Staccato.build_client_id
end
|
The unique client id
@return [String]
|
client_id
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def build_pageview(options = {})
Staccato::Pageview.new(self, options)
end
|
Build a pageview
@param options [Hash] options include:
* path (optional) the path of the current page view
* hostname (optional) the hostname of the current page view
* title (optional) the page title
@return [Pageview]
|
build_pageview
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def build_event(options = {})
Staccato::Event.new(self, options)
end
|
Build an event
@param options [Hash] options include:
* category (optional)
* action (optional)
* label (optional)
* value (optional)
@return [Event]
|
build_event
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def social(options = {})
Staccato::Social.new(self, options).track!
end
|
Track a social event such as a Facebook Like or Twitter Share
@param options [Hash] options include:
* action (required) the action taken, e.g., 'like'
* network (required) the network used, e.g., 'facebook'
* target (required) the target page path, e.g., '/blog/something-awesome'
@return [<Net::HTTPOK] the GA `/collect` endpoint always returns a 200
|
social
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def exception(options = {})
Staccato::Exception.new(self, options).track!
end
|
Track an exception
@param options [Hash] options include:
* description (optional) often the class of exception, e.g., RuntimeException
* fatal (optional) was the exception fatal? boolean, defaults to false
@return [<Net::HTTPOK] the GA `/collect` endpoint always returns a 200
|
exception
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def timing(options = {}, &block)
Staccato::Timing.new(self, options).track!(&block)
end
|
Track timing
@param options [Hash] options include:
* category (optional) e.g., 'runtime'
* variable (optional) e.g., 'database'
* label (optional) e.g., 'query'
* time (recommended) the integer time in milliseconds
* page_load_time (optional)
* dns_time (optional)
* page_download_time (optional)
* redirect_response_time (optional)
* tcp_connect_time (optional)
* server_response_time (optional) most useful on the server-side
@param block [#call] if a block is provided, the time it takes to
run will be recorded and set as the `time` value option, no other
time values will be set.
@return [<Net::HTTPOK] the GA `/collect` endpoint always returns a 200
|
timing
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def build_transaction(options = {})
Staccato::Transaction.new(self, options)
end
|
Build an ecommerce transaction
@return [Transaction]
|
build_transaction
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def build_transaction_item(options = {})
Staccato::TransactionItem.new(self, options)
end
|
Build an item in an ecommerce transaction
@return [TransactionItem]
|
build_transaction_item
|
ruby
|
tpitale/staccato
|
lib/staccato/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/tracker.rb
|
MIT
|
def initialize(uri)
@host = uri.host
@port = uri.port
@socket = UDPSocket.new
end
|
Takes a URI with host/port
e.g.: URI('udp://127.0.0.1:3001')
|
initialize
|
ruby
|
tpitale/staccato
|
lib/staccato/adapter/udp.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/adapter/udp.rb
|
MIT
|
def initialize(measurement_id, api_secret, client_id = nil, options = {})
@measurement_id = measurement_id
@api_secret = api_secret
@client_id = client_id
@adapters = []
self.events = []
end
|
sets up a new tracker
@param measurement_id [String] the measurement id from GA
@param api_secret [String] the required api secret key
@param client_id [String, nil] unique value to track user sessions
@param options [Hash]
|
initialize
|
ruby
|
tpitale/staccato
|
lib/staccato/v4/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/v4/tracker.rb
|
MIT
|
def client_id
@client_id ||= Staccato.build_client_id
end
|
The unique client id
@return [String]
|
client_id
|
ruby
|
tpitale/staccato
|
lib/staccato/v4/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/v4/tracker.rb
|
MIT
|
def add(event_klass, options)
# TODO raise if events reach batch size?
events << event_klass.new(self, options)
end
|
Add an Event instance to the events to be sent
|
add
|
ruby
|
tpitale/staccato
|
lib/staccato/v4/tracker.rb
|
https://github.com/tpitale/staccato/blob/master/lib/staccato/v4/tracker.rb
|
MIT
|
def expression_at(file, line_number, options={})
options = {
:strict => false,
:consume => 0
}.merge!(options)
lines = file.is_a?(Array) ? file : file.each_line.to_a
relevant_lines = lines[(line_number - 1)..-1] || []
extract_first_expression(relevant_lines, options[:consume])
rescue SyntaxError => e
raise if options[:strict]
begin
extract_first_expression(relevant_lines) do |code|
code.gsub(/\#\{.*?\}/, "temp")
end
rescue SyntaxError
raise e
end
end
|
Retrieve the first expression starting on the given line of the given file.
This is useful to get module or method source code.
@param [Array<String>, File, String] file The file to parse, either as a File or as
@param [Integer] line_number The line number at which to look.
NOTE: The first line in a file is
line 1!
@param [Hash] options The optional configuration parameters.
@option options [Boolean] :strict If set to true, then only completely
valid expressions are returned. Otherwise heuristics are used to extract
expressions that may have been valid inside an eval.
@option options [Integer] :consume A number of lines to automatically
consume (add to the expression buffer) without checking for validity.
@return [String] The first complete expression
@raise [SyntaxError] If the first complete expression can't be identified
|
expression_at
|
ruby
|
banister/method_source
|
lib/method_source/code_helpers.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/code_helpers.rb
|
MIT
|
def comment_describing(file, line_number)
lines = file.is_a?(Array) ? file : file.each_line.to_a
extract_last_comment(lines[0..(line_number - 2)])
end
|
Retrieve the comment describing the expression on the given line of the given file.
This is useful to get module or method documentation.
@param [Array<String>, File, String] file The file to parse, either as a File or as
a String or an Array of lines.
@param [Integer] line_number The line number at which to look.
NOTE: The first line in a file is line 1!
@return [String] The comment
|
comment_describing
|
ruby
|
banister/method_source
|
lib/method_source/code_helpers.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/code_helpers.rb
|
MIT
|
def complete_expression?(str)
old_verbose = $VERBOSE
$VERBOSE = nil
catch(:valid) do
eval("BEGIN{throw :valid}\n#{str}")
end
# Assert that a line which ends with a , or \ is incomplete.
str !~ /[,\\]\s*\z/
rescue IncompleteExpression
false
ensure
$VERBOSE = old_verbose
end
|
Determine if a string of code is a complete Ruby expression.
@param [String] code The code to validate.
@return [Boolean] Whether or not the code is a complete Ruby expression.
@raise [SyntaxError] Any SyntaxError that does not represent incompleteness.
@example
complete_expression?("class Hello") #=> false
complete_expression?("class Hello; end") #=> true
complete_expression?("class 123") #=> SyntaxError: unexpected tINTEGER
|
complete_expression?
|
ruby
|
banister/method_source
|
lib/method_source/code_helpers.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/code_helpers.rb
|
MIT
|
def extract_first_expression(lines, consume=0, &block)
code = consume.zero? ? +"" : lines.slice!(0..(consume - 1)).join
lines.each do |v|
code << v
return code if complete_expression?(block ? block.call(code) : code)
end
raise SyntaxError, "unexpected $end"
end
|
Get the first expression from the input.
@param [Array<String>] lines
@param [Integer] consume A number of lines to automatically
consume (add to the expression buffer) without checking for validity.
@yield a clean-up function to run before checking for complete_expression
@return [String] a valid ruby expression
@raise [SyntaxError]
|
extract_first_expression
|
ruby
|
banister/method_source
|
lib/method_source/code_helpers.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/code_helpers.rb
|
MIT
|
def extract_last_comment(lines)
buffer = +""
lines.each do |line|
# Add any line that is a valid ruby comment,
# but clear as soon as we hit a non comment line.
if (line =~ /^\s*#/) || (line =~ /^\s*$/)
buffer << line.lstrip
else
buffer.clear
end
end
buffer
end
|
Get the last comment from the input.
@param [Array<String>] lines
@return [String]
|
extract_last_comment
|
ruby
|
banister/method_source
|
lib/method_source/code_helpers.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/code_helpers.rb
|
MIT
|
def source_location
[__file__, __line__] rescue nil
end
|
Ruby enterprise edition provides all the information that's
needed, in a slightly different way.
|
source_location
|
ruby
|
banister/method_source
|
lib/method_source/source_location.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/source_location.rb
|
MIT
|
def source_location
if @file.nil?
args =[*(1..(arity<-1 ? -arity-1 : arity ))]
set_trace_func method(:trace_func).to_proc
call(*args) rescue nil
set_trace_func nil
@file = File.expand_path(@file) if @file && File.exist?(File.expand_path(@file))
end
[@file, @line] if @file
end
|
Return the source location of a method for Ruby 1.8.
@return [Array] A two element array. First element is the
file, second element is the line in the file where the
method definition is found.
|
source_location
|
ruby
|
banister/method_source
|
lib/method_source/source_location.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/source_location.rb
|
MIT
|
def source_location
[block.file.to_s, block.line]
end
|
Return the source location for a Proc (Rubinius only)
@return [Array] A two element array. First element is the
file, second element is the line in the file where the
proc definition is found.
|
source_location
|
ruby
|
banister/method_source
|
lib/method_source/source_location.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/source_location.rb
|
MIT
|
def source_location
self.to_s =~ /@(.*):(\d+)/
[$1, $2.to_i]
end
|
Return the source location for a Proc (in implementations
without Proc#source_location)
@return [Array] A two element array. First element is the
file, second element is the line in the file where the
proc definition is found.
|
source_location
|
ruby
|
banister/method_source
|
lib/method_source/source_location.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/source_location.rb
|
MIT
|
def source_location
klass = case owner
when Class
owner
when Module
method_owner = owner
Class.new { include(method_owner) }
end
# deal with immediate values
case
when klass == Symbol
return :a.method(name).source_location
when klass == Integer
return 0.method(name).source_location
when klass == TrueClass
return true.method(name).source_location
when klass == FalseClass
return false.method(name).source_location
when klass == NilClass
return nil.method(name).source_location
end
begin
Object.instance_method(:method).bind(klass.allocate).call(name).source_location
rescue TypeError
# Assume we are dealing with a Singleton Class:
# 1. Get the instance object
# 2. Forward the source_location lookup to the instance
instance ||= ObjectSpace.each_object(owner).first
Object.instance_method(:method).bind(instance).call(name).source_location
end
end
|
Return the source location of an instance method for Ruby 1.8.
@return [Array] A two element array. First element is the
file, second element is the line in the file where the
method definition is found.
|
source_location
|
ruby
|
banister/method_source
|
lib/method_source/source_location.rb
|
https://github.com/banister/method_source/blob/master/lib/method_source/source_location.rb
|
MIT
|
def tag(name, **attributes, &)
state = @_state
block_given = block_given?
buffer = state.buffer
unless state.should_render?
yield(self) if block_given
return nil
end
unless Symbol === name
raise Phlex::ArgumentError.new("Expected the tag name to be a Symbol.")
end
if (tag = StandardElements.__registered_elements__[name]) || (tag = name.name.tr("_", "-")).include?("-")
if attributes.length > 0 # with attributes
if block_given # with content block
buffer << "<#{tag}" << (Phlex::ATTRIBUTE_CACHE[attributes] ||= __attributes__(attributes)) << ">"
if tag == "svg"
render Phlex::SVG.new(&)
else
__yield_content__(&)
end
buffer << "</#{tag}>"
else # without content
buffer << "<#{tag}" << (::Phlex::ATTRIBUTE_CACHE[attributes] ||= __attributes__(attributes)) << "></#{tag}>"
end
else # without attributes
if block_given # with content block
buffer << ("<#{tag}>")
if tag == "svg"
render Phlex::SVG.new(&)
else
__yield_content__(&)
end
buffer << "</#{tag}>"
else # without content
buffer << "<#{tag}></#{tag}>"
end
end
elsif (tag = VoidElements.__registered_elements__[name])
if block_given
raise Phlex::ArgumentError.new("Void elements cannot have content blocks.")
end
if attributes.length > 0 # with attributes
buffer << "<#{tag}" << (::Phlex::ATTRIBUTE_CACHE[attributes] ||= __attributes__(attributes)) << ">"
else # without attributes
buffer << "<#{tag}>"
end
nil
else
raise Phlex::ArgumentError.new("Invalid HTML tag: #{name}")
end
end
|
Output an HTML tag dynamically, e.g:
```ruby
@tag_name = :h1
tag(@tag_name, class: "title")
```
|
tag
|
ruby
|
yippee-fun/phlex
|
lib/phlex/html.rb
|
https://github.com/yippee-fun/phlex/blob/master/lib/phlex/html.rb
|
MIT
|
def new(*a, **k, &block)
if block
object = super(*a, **k, &nil)
object.instance_exec { @_content_block = block }
object
else
super
end
end
|
Create a new instance of the component.
@note The block will not be delegated to {#initialize}. Instead, it will be sent to {#view_template} when rendering.
|
new
|
ruby
|
yippee-fun/phlex
|
lib/phlex/sgml.rb
|
https://github.com/yippee-fun/phlex/blob/master/lib/phlex/sgml.rb
|
MIT
|
def full_data_range(ds)
return if max_value == false
ds.each_with_index do |mds, mds_index|
mds[:min_value] ||= min_value
mds[:max_value] ||= max_value
if mds_index == 0 && type.to_s == 'bar'
# TODO: unless you specify a zero line (using chp or chds),
# the min_value of a bar chart is always 0.
#mds[:min_value] ||= mds[:data].first.to_a.compact.min
mds[:min_value] ||= 0
end
if (mds_index == 0 && type.to_s == 'bar' &&
!grouped && mds[:data].first.is_a?(Array))
totals = []
mds[:data].each do |l|
l.each_with_index do |v, index|
next if v.nil?
totals[index] ||= 0
totals[index] += v
end
end
mds[:max_value] ||= totals.compact.max
else
all = mds[:data].flatten.compact
# default min value should be 0 unless set to auto
if mds[:min_value] == 'auto'
mds[:min_value] = all.min
else
min = all.min
mds[:min_value] ||= (min && min < 0 ? min : 0)
end
mds[:max_value] ||= all.max
end
end
unless axis_range
@calculated_axis_range = true
@axis_range = ds.map{|mds| [mds[:min_value], mds[:max_value]]}
if dimensions == 1 && (type.to_s != 'bar' || horizontal)
tmp = axis_range.fetch(0, [])
@axis_range[0] = axis_range.fetch(1, [])
@axis_range[1] = tmp
end
end
# return [min, max] unless (min.nil? || max.nil?)
# @max = (max_value.nil? || max_value == 'auto') ? ds.compact.map{|mds| mds.compact.max}.max : max_value
#
# if min_value.nil?
# min_ds_value = ds.compact.map{|mds| mds.compact.min}.min || 0
# @min = (min_ds_value < 0) ? min_ds_value : 0
# else
# @min = min_value == 'auto' ? ds.compact.map{|mds| mds.compact.min}.min || 0 : min_value
# end
# @axis_range = [[min,max]]
end
|
returns the full data range as an array
it also sets the data range if not defined
|
full_data_range
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def datasets
datasets = []
dataset.each do |d|
if d[:data].first.is_a?(Array)
datasets += d[:data]
else
datasets << d[:data]
end
end
datasets
end
|
Sets of data to handle multiple sets
|
datasets
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def fetch
url = URI.parse(self.class.url(use_ssl))
req = Net::HTTP::Post.new(url.path)
req.body = query_builder
req.content_type = 'application/x-www-form-urlencoded'
http = Net::HTTP.new(url.host, url.port)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER if use_ssl
http.use_ssl = use_ssl
http.start {|resp| resp.request(req) }.body
end
|
Returns the chart's generated PNG as a blob. (borrowed from John's gchart.rubyforge.org)
|
fetch
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def write
io_or_file = filename || self.class.default_filename
return io_or_file.write(fetch) if io_or_file.respond_to?(:write)
open(io_or_file, "wb+") { |io| io.write(fetch) }
end
|
Writes the chart's generated PNG to a file. (borrowed from John's gchart.rubyforge.org)
|
write
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def set_title
title_params = "chtt=#{title}".gsub(/\|/,"\n")
unless (title_color.nil? && title_size.nil? && title_alignment.nil?)
title_params << "&chts=" + (color, size, alignment = (title_color || '454545'), title_size, (title_alignment.to_s[0,1] || 'c')).compact.join(',')
end
title_params
end
|
The title size cannot be set without specifying a color.
A dark key will be used for the title color if no color is specified
|
set_title
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def set_bar_width_and_spacing
width_and_spacing_values = case bar_width_and_spacing
when String
bar_width_and_spacing
when Array
bar_width_and_spacing.join(',')
when Hash
width = bar_width_and_spacing[:width] || 23
spacing = bar_width_and_spacing[:spacing] || 4
group_spacing = bar_width_and_spacing[:group_spacing] || 8
[width,spacing,group_spacing].join(',')
else
bar_width_and_spacing.to_s
end
"chbh=#{width_and_spacing_values}"
end
|
set bar spacing
chbh=
<bar width in pixels>,
<optional space between bars in a group>,
<optional space between groups>
|
set_bar_width_and_spacing
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def set_legend
if type.to_s =~ /meter/
@labels = legend
return set_labels
end
if legend.is_a?(Array)
"chdl=#{@legend.map{|label| "#{CGI::escape(label.to_s)}"}.join('|')}"
else
"chdl=#{legend}"
end
end
|
A chart can have one or many legends.
Gchart.line(:legend => 'label')
or
Gchart.line(:legend => ['first label', 'last label'])
|
set_legend
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def set_axis_range
# a passed axis_range should look like:
# [[10,100]] or [[10,100,4]] or [[10,100], [20,300]]
# in the second example, 4 is the interval
set = @calculated_axis_range ? datasets : axis_range || datasets
return unless set && set.respond_to?(:each) && set.find {|o| o}.respond_to?(:each)
'chxr=' + set.enum_for(:each_with_index).map do |axis_range, index|
next nil if axis_range.nil? # ignore this axis
min, max, step = axis_range
if axis_range.size > 3 || step && max && step > max # this is a full series
max = axis_range.compact.max
step = nil
end
[index, (min_value || min || 0), (max_value || max), step].compact.join(',')
end.compact.join("|")
end
|
http://code.google.com/apis/chart/labels.html#axis_range
Specify a range for axis labels
|
set_axis_range
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def convert_dataset(ds)
if dimensions == 2
# valid inputs include:
# an array of >=2 arrays, or an array of >=2 hashes
ds = ds.map do |d|
d.is_a?(Hash) ? d : {:data => d}
end
elsif dimensions == 1
# valid inputs include:
# a hash, an array of data, an array of >=1 array, or an array of >=1 hash
if ds.is_a?(Hash)
ds = [ds]
elsif not ds.first.is_a?(Hash)
ds = [{:data => ds}]
end
end
ds
end
|
Turns input into an array of axis hashes, dependent on the chart type
|
convert_dataset
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def simple_encoding
"s" + number_visible + ":" + encode_scaled_dataset(self.class.simple_chars, '_')
end
|
http://code.google.com/apis/chart/#simple
Simple encoding has a resolution of 62 different values.
Allowing five pixels per data point, this is sufficient for line and bar charts up
to about 300 pixels. Simple encoding is suitable for all other types of chart regardless of size.
|
simple_encoding
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def extended_encoding
"e" + number_visible + ":" + encode_scaled_dataset(self.class.ext_pairs, '__')
end
|
http://code.google.com/apis/chart/#extended
Extended encoding has a resolution of 4,096 different values
and is best used for large charts where a large data range is required.
|
extended_encoding
|
ruby
|
mattetti/googlecharts
|
lib/gchart.rb
|
https://github.com/mattetti/googlecharts/blob/master/lib/gchart.rb
|
MIT
|
def home
if File.writable?(Dir.home)
Dir.home
else
Etc.getpwuid(Process.uid).dir
end
end
|
On some platforms `Dir.home` or `ENV['HOME']` does not return home directory of user.
this is especially true, after effective and real user id of process
has been changed.
@return [String] home directory of the user
|
home
|
ruby
|
codemancers/invoker
|
lib/invoker.rb
|
https://github.com/codemancers/invoker/blob/master/lib/invoker.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.