repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
nathanl/authority
lib/authority/controller.rb
Authority.Controller.authorize_action_for
def authorize_action_for(authority_resource, *options) # `action_name` comes from ActionController authority_action = self.class.authority_action_map[action_name.to_sym] if authority_action.nil? raise MissingAction.new("No authority action defined for #{action_name}") end Authority.enforce(authority_action, authority_resource, authority_user, *options) # This method is always invoked, but will only log if it's overriden authority_success(authority_user, authority_action, authority_resource) self.authorization_performed = true end
ruby
def authorize_action_for(authority_resource, *options) # `action_name` comes from ActionController authority_action = self.class.authority_action_map[action_name.to_sym] if authority_action.nil? raise MissingAction.new("No authority action defined for #{action_name}") end Authority.enforce(authority_action, authority_resource, authority_user, *options) # This method is always invoked, but will only log if it's overriden authority_success(authority_user, authority_action, authority_resource) self.authorization_performed = true end
[ "def", "authorize_action_for", "(", "authority_resource", ",", "*", "options", ")", "# `action_name` comes from ActionController", "authority_action", "=", "self", ".", "class", ".", "authority_action_map", "[", "action_name", ".", "to_sym", "]", "if", "authority_action", ".", "nil?", "raise", "MissingAction", ".", "new", "(", "\"No authority action defined for #{action_name}\"", ")", "end", "Authority", ".", "enforce", "(", "authority_action", ",", "authority_resource", ",", "authority_user", ",", "options", ")", "# This method is always invoked, but will only log if it's overriden", "authority_success", "(", "authority_user", ",", "authority_action", ",", "authority_resource", ")", "self", ".", "authorization_performed", "=", "true", "end" ]
To be run in a `before_filter`; ensure this controller action is allowed for the user Can be used directly within a controller action as well, given an instance or class with or without options to delegate to the authorizer. @param [Class] authority_resource, the model class associated with this controller @param [Hash] options, arbitrary options hash to forward up the chain to the authorizer @raise [MissingAction] if controller action isn't a key in `config.controller_action_map`
[ "To", "be", "run", "in", "a", "before_filter", ";", "ensure", "this", "controller", "action", "is", "allowed", "for", "the", "user", "Can", "be", "used", "directly", "within", "a", "controller", "action", "as", "well", "given", "an", "instance", "or", "class", "with", "or", "without", "options", "to", "delegate", "to", "the", "authorizer", "." ]
35176d8bffb99824bc49e8bb5f2ddfe54ff863ad
https://github.com/nathanl/authority/blob/35176d8bffb99824bc49e8bb5f2ddfe54ff863ad/lib/authority/controller.rb#L128-L141
train
nathanl/authority
lib/authority/controller.rb
Authority.Controller.authority_forbidden
def authority_forbidden(error) Authority.logger.warn(error.message) render :file => Rails.root.join('public', '403.html'), :status => 403, :layout => false end
ruby
def authority_forbidden(error) Authority.logger.warn(error.message) render :file => Rails.root.join('public', '403.html'), :status => 403, :layout => false end
[ "def", "authority_forbidden", "(", "error", ")", "Authority", ".", "logger", ".", "warn", "(", "error", ".", "message", ")", "render", ":file", "=>", "Rails", ".", "root", ".", "join", "(", "'public'", ",", "'403.html'", ")", ",", ":status", "=>", "403", ",", ":layout", "=>", "false", "end" ]
Renders a static file to minimize the chances of further errors. @param [Exception] error, an error that indicates the user tried to perform a forbidden action.
[ "Renders", "a", "static", "file", "to", "minimize", "the", "chances", "of", "further", "errors", "." ]
35176d8bffb99824bc49e8bb5f2ddfe54ff863ad
https://github.com/nathanl/authority/blob/35176d8bffb99824bc49e8bb5f2ddfe54ff863ad/lib/authority/controller.rb#L146-L149
train
nathanl/authority
lib/authority/controller.rb
Authority.Controller.run_authorization_check
def run_authorization_check if instance_authority_resource.is_a?(Array) # Array includes options; pass as separate args authorize_action_for(*instance_authority_resource, *authority_arguments) else # *resource would be interpreted as resource.to_a, which is wrong and # actually triggers a query if it's a Sequel model authorize_action_for(instance_authority_resource, *authority_arguments) end end
ruby
def run_authorization_check if instance_authority_resource.is_a?(Array) # Array includes options; pass as separate args authorize_action_for(*instance_authority_resource, *authority_arguments) else # *resource would be interpreted as resource.to_a, which is wrong and # actually triggers a query if it's a Sequel model authorize_action_for(instance_authority_resource, *authority_arguments) end end
[ "def", "run_authorization_check", "if", "instance_authority_resource", ".", "is_a?", "(", "Array", ")", "# Array includes options; pass as separate args", "authorize_action_for", "(", "instance_authority_resource", ",", "authority_arguments", ")", "else", "# *resource would be interpreted as resource.to_a, which is wrong and", "# actually triggers a query if it's a Sequel model", "authorize_action_for", "(", "instance_authority_resource", ",", "authority_arguments", ")", "end", "end" ]
The `before_filter` that will be setup to run when the class method `authorize_actions_for` is called
[ "The", "before_filter", "that", "will", "be", "setup", "to", "run", "when", "the", "class", "method", "authorize_actions_for", "is", "called" ]
35176d8bffb99824bc49e8bb5f2ddfe54ff863ad
https://github.com/nathanl/authority/blob/35176d8bffb99824bc49e8bb5f2ddfe54ff863ad/lib/authority/controller.rb#L160-L169
train
theforeman/foreman_docker
app/models/service/registry_api.rb
Service.RegistryApi.search
def search(query) get('/v1/search'.freeze, { q: query }) rescue => e logger.warn "API v1 - Search failed #{e.backtrace}" { 'results' => catalog(query) } end
ruby
def search(query) get('/v1/search'.freeze, { q: query }) rescue => e logger.warn "API v1 - Search failed #{e.backtrace}" { 'results' => catalog(query) } end
[ "def", "search", "(", "query", ")", "get", "(", "'/v1/search'", ".", "freeze", ",", "{", "q", ":", "query", "}", ")", "rescue", "=>", "e", "logger", ".", "warn", "\"API v1 - Search failed #{e.backtrace}\"", "{", "'results'", "=>", "catalog", "(", "query", ")", "}", "end" ]
Since the Registry API v2 does not support a search the v1 endpoint is used Newer registries will fail, the v2 catalog endpoint is used
[ "Since", "the", "Registry", "API", "v2", "does", "not", "support", "a", "search", "the", "v1", "endpoint", "is", "used", "Newer", "registries", "will", "fail", "the", "v2", "catalog", "endpoint", "is", "used" ]
f785e5ae3f44e9f5c60f30dab351d30d2a1e1038
https://github.com/theforeman/foreman_docker/blob/f785e5ae3f44e9f5c60f30dab351d30d2a1e1038/app/models/service/registry_api.rb#L34-L39
train
NUBIC/surveyor
lib/surveyor/acts_as_response.rb
Surveyor.ActsAsResponse.as
def as(type_symbol) return case type_symbol.to_sym when :string, :text, :integer, :float, :datetime self.send("#{type_symbol}_value".to_sym) when :date self.datetime_value.nil? ? nil : self.datetime_value.to_date when :time self.datetime_value.nil? ? nil : self.datetime_value.to_time else # :answer_id self.answer_id end end
ruby
def as(type_symbol) return case type_symbol.to_sym when :string, :text, :integer, :float, :datetime self.send("#{type_symbol}_value".to_sym) when :date self.datetime_value.nil? ? nil : self.datetime_value.to_date when :time self.datetime_value.nil? ? nil : self.datetime_value.to_time else # :answer_id self.answer_id end end
[ "def", "as", "(", "type_symbol", ")", "return", "case", "type_symbol", ".", "to_sym", "when", ":string", ",", ":text", ",", ":integer", ",", ":float", ",", ":datetime", "self", ".", "send", "(", "\"#{type_symbol}_value\"", ".", "to_sym", ")", "when", ":date", "self", ".", "datetime_value", ".", "nil?", "?", "nil", ":", "self", ".", "datetime_value", ".", "to_date", "when", ":time", "self", ".", "datetime_value", ".", "nil?", "?", "nil", ":", "self", ".", "datetime_value", ".", "to_time", "else", "# :answer_id", "self", ".", "answer_id", "end", "end" ]
Returns the response as a particular response_class type
[ "Returns", "the", "response", "as", "a", "particular", "response_class", "type" ]
d4fe8df2586ba26126bac3c4b3498e67ba813baf
https://github.com/NUBIC/surveyor/blob/d4fe8df2586ba26126bac3c4b3498e67ba813baf/lib/surveyor/acts_as_response.rb#L6-L17
train
NUBIC/surveyor
lib/surveyor/parser.rb
Surveyor.Parser.method_missing
def method_missing(missing_method, *args, &block) method_name, reference_identifier = missing_method.to_s.split("_", 2) type = full(method_name) Surveyor::Parser.raise_error( "\"#{type}\" is not a surveyor method." )if !%w(survey survey_translation survey_section question_group question dependency dependency_condition answer validation validation_condition).include?(type) Surveyor::Parser.rake_trace(reference_identifier.blank? ? "#{type} #{args.map(&:inspect).join ', '}" : "#{type}_#{reference_identifier} #{args.map(&:inspect).join ', '}", block_models.include?(type) ? 2 : 0) # check for blocks Surveyor::Parser.raise_error "A #{type.humanize.downcase} should take a block" if block_models.include?(type) && !block_given? Surveyor::Parser.raise_error "A #{type.humanize.downcase} doesn't take a block" if !block_models.include?(type) && block_given? # parse and build type.classify.constantize.new.extend("SurveyorParser#{type.classify}Methods".constantize).parse_and_build(context, args, method_name, reference_identifier) # evaluate and clear context for block models if block_models.include?(type) self.instance_eval(&block) if type == 'survey' resolve_dependency_condition_references resolve_question_correct_answers report_lost_and_duplicate_references report_missing_default_locale Surveyor::Parser.rake_trace("", -2) if context[:survey].save Surveyor::Parser.rake_trace "Survey saved." else Surveyor::Parser.raise_error "Survey not saved: #{context[:survey].errors.full_messages.join(", ")}" end else Surveyor::Parser.rake_trace("", -2) context[type.to_sym].clear(context) end end end
ruby
def method_missing(missing_method, *args, &block) method_name, reference_identifier = missing_method.to_s.split("_", 2) type = full(method_name) Surveyor::Parser.raise_error( "\"#{type}\" is not a surveyor method." )if !%w(survey survey_translation survey_section question_group question dependency dependency_condition answer validation validation_condition).include?(type) Surveyor::Parser.rake_trace(reference_identifier.blank? ? "#{type} #{args.map(&:inspect).join ', '}" : "#{type}_#{reference_identifier} #{args.map(&:inspect).join ', '}", block_models.include?(type) ? 2 : 0) # check for blocks Surveyor::Parser.raise_error "A #{type.humanize.downcase} should take a block" if block_models.include?(type) && !block_given? Surveyor::Parser.raise_error "A #{type.humanize.downcase} doesn't take a block" if !block_models.include?(type) && block_given? # parse and build type.classify.constantize.new.extend("SurveyorParser#{type.classify}Methods".constantize).parse_and_build(context, args, method_name, reference_identifier) # evaluate and clear context for block models if block_models.include?(type) self.instance_eval(&block) if type == 'survey' resolve_dependency_condition_references resolve_question_correct_answers report_lost_and_duplicate_references report_missing_default_locale Surveyor::Parser.rake_trace("", -2) if context[:survey].save Surveyor::Parser.rake_trace "Survey saved." else Surveyor::Parser.raise_error "Survey not saved: #{context[:survey].errors.full_messages.join(", ")}" end else Surveyor::Parser.rake_trace("", -2) context[type.to_sym].clear(context) end end end
[ "def", "method_missing", "(", "missing_method", ",", "*", "args", ",", "&", "block", ")", "method_name", ",", "reference_identifier", "=", "missing_method", ".", "to_s", ".", "split", "(", "\"_\"", ",", "2", ")", "type", "=", "full", "(", "method_name", ")", "Surveyor", "::", "Parser", ".", "raise_error", "(", "\"\\\"#{type}\\\" is not a surveyor method.\"", ")", "if", "!", "%w(", "survey", "survey_translation", "survey_section", "question_group", "question", "dependency", "dependency_condition", "answer", "validation", "validation_condition", ")", ".", "include?", "(", "type", ")", "Surveyor", "::", "Parser", ".", "rake_trace", "(", "reference_identifier", ".", "blank?", "?", "\"#{type} #{args.map(&:inspect).join ', '}\"", ":", "\"#{type}_#{reference_identifier} #{args.map(&:inspect).join ', '}\"", ",", "block_models", ".", "include?", "(", "type", ")", "?", "2", ":", "0", ")", "# check for blocks", "Surveyor", "::", "Parser", ".", "raise_error", "\"A #{type.humanize.downcase} should take a block\"", "if", "block_models", ".", "include?", "(", "type", ")", "&&", "!", "block_given?", "Surveyor", "::", "Parser", ".", "raise_error", "\"A #{type.humanize.downcase} doesn't take a block\"", "if", "!", "block_models", ".", "include?", "(", "type", ")", "&&", "block_given?", "# parse and build", "type", ".", "classify", ".", "constantize", ".", "new", ".", "extend", "(", "\"SurveyorParser#{type.classify}Methods\"", ".", "constantize", ")", ".", "parse_and_build", "(", "context", ",", "args", ",", "method_name", ",", "reference_identifier", ")", "# evaluate and clear context for block models", "if", "block_models", ".", "include?", "(", "type", ")", "self", ".", "instance_eval", "(", "block", ")", "if", "type", "==", "'survey'", "resolve_dependency_condition_references", "resolve_question_correct_answers", "report_lost_and_duplicate_references", "report_missing_default_locale", "Surveyor", "::", "Parser", ".", "rake_trace", "(", "\"\"", ",", "-", "2", ")", "if", "context", "[", ":survey", "]", ".", "save", "Surveyor", "::", "Parser", ".", "rake_trace", "\"Survey saved.\"", "else", "Surveyor", "::", "Parser", ".", "raise_error", "\"Survey not saved: #{context[:survey].errors.full_messages.join(\", \")}\"", "end", "else", "Surveyor", "::", "Parser", ".", "rake_trace", "(", "\"\"", ",", "-", "2", ")", "context", "[", "type", ".", "to_sym", "]", ".", "clear", "(", "context", ")", "end", "end", "end" ]
This method_missing does all the heavy lifting for the DSL
[ "This", "method_missing", "does", "all", "the", "heavy", "lifting", "for", "the", "DSL" ]
d4fe8df2586ba26126bac3c4b3498e67ba813baf
https://github.com/NUBIC/surveyor/blob/d4fe8df2586ba26126bac3c4b3498e67ba813baf/lib/surveyor/parser.rb#L69-L103
train
rgrove/larch
lib/larch/config.rb
Larch.Config.validate
def validate ['from', 'to'].each do |s| raise Error, "'#{s}' must be a valid IMAP URI (e.g. imap://example.com)" unless fetch(s) =~ IMAP::REGEX_URI end unless Logger::LEVELS.has_key?(verbosity.to_sym) raise Error, "'verbosity' must be one of: #{Logger::LEVELS.keys.join(', ')}" end if exclude_file raise Error, "exclude file not found: #{exclude_file}" unless File.file?(exclude_file) raise Error, "exclude file cannot be read: #{exclude_file}" unless File.readable?(exclude_file) end if @cached['all'] || @cached['all-subscribed'] # A specific source folder wins over 'all' and 'all-subscribed' if @cached['from-folder'] @cached['all'] = false @cached['all-subscribed'] = false @cached['to-folder'] ||= @cached['from-folder'] elsif @cached['all'] && @cached['all-subscribed'] # 'all' wins over 'all-subscribed' @cached['all-subscribed'] = false end # 'no-recurse' is not compatible with 'all' and 'all-subscribed' raise Error, "'no-recurse' option cannot be used with 'all' or 'all-subscribed'" if @cached['no-recurse'] else @cached['from-folder'] ||= 'INBOX' @cached['to-folder'] ||= 'INBOX' end @cached['exclude'].flatten! end
ruby
def validate ['from', 'to'].each do |s| raise Error, "'#{s}' must be a valid IMAP URI (e.g. imap://example.com)" unless fetch(s) =~ IMAP::REGEX_URI end unless Logger::LEVELS.has_key?(verbosity.to_sym) raise Error, "'verbosity' must be one of: #{Logger::LEVELS.keys.join(', ')}" end if exclude_file raise Error, "exclude file not found: #{exclude_file}" unless File.file?(exclude_file) raise Error, "exclude file cannot be read: #{exclude_file}" unless File.readable?(exclude_file) end if @cached['all'] || @cached['all-subscribed'] # A specific source folder wins over 'all' and 'all-subscribed' if @cached['from-folder'] @cached['all'] = false @cached['all-subscribed'] = false @cached['to-folder'] ||= @cached['from-folder'] elsif @cached['all'] && @cached['all-subscribed'] # 'all' wins over 'all-subscribed' @cached['all-subscribed'] = false end # 'no-recurse' is not compatible with 'all' and 'all-subscribed' raise Error, "'no-recurse' option cannot be used with 'all' or 'all-subscribed'" if @cached['no-recurse'] else @cached['from-folder'] ||= 'INBOX' @cached['to-folder'] ||= 'INBOX' end @cached['exclude'].flatten! end
[ "def", "validate", "[", "'from'", ",", "'to'", "]", ".", "each", "do", "|", "s", "|", "raise", "Error", ",", "\"'#{s}' must be a valid IMAP URI (e.g. imap://example.com)\"", "unless", "fetch", "(", "s", ")", "=~", "IMAP", "::", "REGEX_URI", "end", "unless", "Logger", "::", "LEVELS", ".", "has_key?", "(", "verbosity", ".", "to_sym", ")", "raise", "Error", ",", "\"'verbosity' must be one of: #{Logger::LEVELS.keys.join(', ')}\"", "end", "if", "exclude_file", "raise", "Error", ",", "\"exclude file not found: #{exclude_file}\"", "unless", "File", ".", "file?", "(", "exclude_file", ")", "raise", "Error", ",", "\"exclude file cannot be read: #{exclude_file}\"", "unless", "File", ".", "readable?", "(", "exclude_file", ")", "end", "if", "@cached", "[", "'all'", "]", "||", "@cached", "[", "'all-subscribed'", "]", "# A specific source folder wins over 'all' and 'all-subscribed'", "if", "@cached", "[", "'from-folder'", "]", "@cached", "[", "'all'", "]", "=", "false", "@cached", "[", "'all-subscribed'", "]", "=", "false", "@cached", "[", "'to-folder'", "]", "||=", "@cached", "[", "'from-folder'", "]", "elsif", "@cached", "[", "'all'", "]", "&&", "@cached", "[", "'all-subscribed'", "]", "# 'all' wins over 'all-subscribed'", "@cached", "[", "'all-subscribed'", "]", "=", "false", "end", "# 'no-recurse' is not compatible with 'all' and 'all-subscribed'", "raise", "Error", ",", "\"'no-recurse' option cannot be used with 'all' or 'all-subscribed'\"", "if", "@cached", "[", "'no-recurse'", "]", "else", "@cached", "[", "'from-folder'", "]", "||=", "'INBOX'", "@cached", "[", "'to-folder'", "]", "||=", "'INBOX'", "end", "@cached", "[", "'exclude'", "]", ".", "flatten!", "end" ]
Validates the config and resolves conflicting settings.
[ "Validates", "the", "config", "and", "resolves", "conflicting", "settings", "." ]
64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42
https://github.com/rgrove/larch/blob/64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42/lib/larch/config.rb#L73-L108
train
rgrove/larch
lib/larch/config.rb
Larch.Config.cache_config
def cache_config @cached = {} @lookup.reverse.each do |c| c.each {|k, v| @cached[k] = config_merge(@cached[k] || {}, v) } end end
ruby
def cache_config @cached = {} @lookup.reverse.each do |c| c.each {|k, v| @cached[k] = config_merge(@cached[k] || {}, v) } end end
[ "def", "cache_config", "@cached", "=", "{", "}", "@lookup", ".", "reverse", ".", "each", "do", "|", "c", "|", "c", ".", "each", "{", "|", "k", ",", "v", "|", "@cached", "[", "k", "]", "=", "config_merge", "(", "@cached", "[", "k", "]", "||", "{", "}", ",", "v", ")", "}", "end", "end" ]
Merges configs such that those earlier in the lookup chain override those later in the chain.
[ "Merges", "configs", "such", "that", "those", "earlier", "in", "the", "lookup", "chain", "override", "those", "later", "in", "the", "chain", "." ]
64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42
https://github.com/rgrove/larch/blob/64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42/lib/larch/config.rb#L114-L120
train
rgrove/larch
lib/larch/imap.rb
Larch.IMAP.safely
def safely safe_connect retries = 0 begin yield rescue Errno::ECONNABORTED, Errno::ECONNRESET, Errno::ENOTCONN, Errno::EPIPE, Errno::ETIMEDOUT, IOError, Net::IMAP::ByeResponseError, OpenSSL::SSL::SSLError => e raise unless (retries += 1) <= @options[:max_retries] warning "#{e.class.name}: #{e.message} (reconnecting)" reset sleep 1 * retries safe_connect retry rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError, Net::IMAP::ResponseParseError => e raise unless (retries += 1) <= @options[:max_retries] warning "#{e.class.name}: #{e.message} (will retry)" sleep 1 * retries retry end rescue Larch::Error => e raise rescue Net::IMAP::Error => e raise Error, "#{e.class.name}: #{e.message} (giving up)" rescue => e raise FatalError, "#{e.class.name}: #{e.message} (cannot recover)" end
ruby
def safely safe_connect retries = 0 begin yield rescue Errno::ECONNABORTED, Errno::ECONNRESET, Errno::ENOTCONN, Errno::EPIPE, Errno::ETIMEDOUT, IOError, Net::IMAP::ByeResponseError, OpenSSL::SSL::SSLError => e raise unless (retries += 1) <= @options[:max_retries] warning "#{e.class.name}: #{e.message} (reconnecting)" reset sleep 1 * retries safe_connect retry rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError, Net::IMAP::ResponseParseError => e raise unless (retries += 1) <= @options[:max_retries] warning "#{e.class.name}: #{e.message} (will retry)" sleep 1 * retries retry end rescue Larch::Error => e raise rescue Net::IMAP::Error => e raise Error, "#{e.class.name}: #{e.message} (giving up)" rescue => e raise FatalError, "#{e.class.name}: #{e.message} (cannot recover)" end
[ "def", "safely", "safe_connect", "retries", "=", "0", "begin", "yield", "rescue", "Errno", "::", "ECONNABORTED", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "ENOTCONN", ",", "Errno", "::", "EPIPE", ",", "Errno", "::", "ETIMEDOUT", ",", "IOError", ",", "Net", "::", "IMAP", "::", "ByeResponseError", ",", "OpenSSL", "::", "SSL", "::", "SSLError", "=>", "e", "raise", "unless", "(", "retries", "+=", "1", ")", "<=", "@options", "[", ":max_retries", "]", "warning", "\"#{e.class.name}: #{e.message} (reconnecting)\"", "reset", "sleep", "1", "*", "retries", "safe_connect", "retry", "rescue", "Net", "::", "IMAP", "::", "BadResponseError", ",", "Net", "::", "IMAP", "::", "NoResponseError", ",", "Net", "::", "IMAP", "::", "ResponseParseError", "=>", "e", "raise", "unless", "(", "retries", "+=", "1", ")", "<=", "@options", "[", ":max_retries", "]", "warning", "\"#{e.class.name}: #{e.message} (will retry)\"", "sleep", "1", "*", "retries", "retry", "end", "rescue", "Larch", "::", "Error", "=>", "e", "raise", "rescue", "Net", "::", "IMAP", "::", "Error", "=>", "e", "raise", "Error", ",", "\"#{e.class.name}: #{e.message} (giving up)\"", "rescue", "=>", "e", "raise", "FatalError", ",", "\"#{e.class.name}: #{e.message} (cannot recover)\"", "end" ]
Connect if necessary, execute the given block, retry if a recoverable error occurs, die if an unrecoverable error occurs.
[ "Connect", "if", "necessary", "execute", "the", "given", "block", "retry", "if", "a", "recoverable", "error", "occurs", "die", "if", "an", "unrecoverable", "error", "occurs", "." ]
64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42
https://github.com/rgrove/larch/blob/64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42/lib/larch/imap.rb#L185-L231
train
rgrove/larch
lib/larch/imap.rb
Larch.IMAP.uri_mailbox
def uri_mailbox mb = @uri.path[1..-1] mb.nil? || mb.empty? ? nil : CGI.unescape(mb) end
ruby
def uri_mailbox mb = @uri.path[1..-1] mb.nil? || mb.empty? ? nil : CGI.unescape(mb) end
[ "def", "uri_mailbox", "mb", "=", "@uri", ".", "path", "[", "1", "..", "-", "1", "]", "mb", ".", "nil?", "||", "mb", ".", "empty?", "?", "nil", ":", "CGI", ".", "unescape", "(", "mb", ")", "end" ]
Gets the IMAP mailbox specified in the URI, or +nil+ if none.
[ "Gets", "the", "IMAP", "mailbox", "specified", "in", "the", "URI", "or", "+", "nil", "+", "if", "none", "." ]
64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42
https://github.com/rgrove/larch/blob/64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42/lib/larch/imap.rb#L244-L247
train
rgrove/larch
lib/larch/imap.rb
Larch.IMAP.check_quirks
def check_quirks return unless @conn && @conn.greeting.kind_of?(Net::IMAP::UntaggedResponse) && @conn.greeting.data.kind_of?(Net::IMAP::ResponseText) if @conn.greeting.data.text =~ /^Gimap ready/ @quirks[:gmail] = true debug "looks like Gmail" elsif host =~ /^imap(?:-ssl)?\.mail\.yahoo\.com$/ @quirks[:yahoo] = true debug "looks like Yahoo! Mail" elsif host =~ /emailsrvr\.com/ @quirks[:rackspace] = true debug "looks like Rackspace Mail" end end
ruby
def check_quirks return unless @conn && @conn.greeting.kind_of?(Net::IMAP::UntaggedResponse) && @conn.greeting.data.kind_of?(Net::IMAP::ResponseText) if @conn.greeting.data.text =~ /^Gimap ready/ @quirks[:gmail] = true debug "looks like Gmail" elsif host =~ /^imap(?:-ssl)?\.mail\.yahoo\.com$/ @quirks[:yahoo] = true debug "looks like Yahoo! Mail" elsif host =~ /emailsrvr\.com/ @quirks[:rackspace] = true debug "looks like Rackspace Mail" end end
[ "def", "check_quirks", "return", "unless", "@conn", "&&", "@conn", ".", "greeting", ".", "kind_of?", "(", "Net", "::", "IMAP", "::", "UntaggedResponse", ")", "&&", "@conn", ".", "greeting", ".", "data", ".", "kind_of?", "(", "Net", "::", "IMAP", "::", "ResponseText", ")", "if", "@conn", ".", "greeting", ".", "data", ".", "text", "=~", "/", "/", "@quirks", "[", ":gmail", "]", "=", "true", "debug", "\"looks like Gmail\"", "elsif", "host", "=~", "/", "\\.", "\\.", "\\.", "/", "@quirks", "[", ":yahoo", "]", "=", "true", "debug", "\"looks like Yahoo! Mail\"", "elsif", "host", "=~", "/", "\\.", "/", "@quirks", "[", ":rackspace", "]", "=", "true", "debug", "\"looks like Rackspace Mail\"", "end", "end" ]
Tries to identify server implementations with certain quirks that we'll need to work around.
[ "Tries", "to", "identify", "server", "implementations", "with", "certain", "quirks", "that", "we", "ll", "need", "to", "work", "around", "." ]
64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42
https://github.com/rgrove/larch/blob/64eb3bd1e3d3335a52e656c7641d9b5b10d6ed42/lib/larch/imap.rb#L258-L275
train
autoforce/APIcasso
app/controllers/apicasso/crud_controller.rb
Apicasso.CrudController.set_object
def set_object id = params[:id] @object = resource.friendly.find(id) rescue NoMethodError @object = resource.find(id) ensure authorize! action_to_cancancan, @object end
ruby
def set_object id = params[:id] @object = resource.friendly.find(id) rescue NoMethodError @object = resource.find(id) ensure authorize! action_to_cancancan, @object end
[ "def", "set_object", "id", "=", "params", "[", ":id", "]", "@object", "=", "resource", ".", "friendly", ".", "find", "(", "id", ")", "rescue", "NoMethodError", "@object", "=", "resource", ".", "find", "(", "id", ")", "ensure", "authorize!", "action_to_cancancan", ",", "@object", "end" ]
Common setup to stablish which object this request is querying
[ "Common", "setup", "to", "stablish", "which", "object", "this", "request", "is", "querying" ]
a95b5fc894eeacd71271ccf33f05d286b5c32b9f
https://github.com/autoforce/APIcasso/blob/a95b5fc894eeacd71271ccf33f05d286b5c32b9f/app/controllers/apicasso/crud_controller.rb#L87-L94
train
autoforce/APIcasso
app/controllers/apicasso/crud_controller.rb
Apicasso.CrudController.set_records
def set_records authorize! :read, resource.name.underscore.to_sym @records = request_collection.ransack(parsed_query).result @object = request_collection.new key_scope_records reorder_records if params[:sort].present? select_fields if params[:select].present? include_relations if params[:include].present? end
ruby
def set_records authorize! :read, resource.name.underscore.to_sym @records = request_collection.ransack(parsed_query).result @object = request_collection.new key_scope_records reorder_records if params[:sort].present? select_fields if params[:select].present? include_relations if params[:include].present? end
[ "def", "set_records", "authorize!", ":read", ",", "resource", ".", "name", ".", "underscore", ".", "to_sym", "@records", "=", "request_collection", ".", "ransack", "(", "parsed_query", ")", ".", "result", "@object", "=", "request_collection", ".", "new", "key_scope_records", "reorder_records", "if", "params", "[", ":sort", "]", ".", "present?", "select_fields", "if", "params", "[", ":select", "]", ".", "present?", "include_relations", "if", "params", "[", ":include", "]", ".", "present?", "end" ]
Used to setup the records from the selected resource that are going to be rendered, if authorized
[ "Used", "to", "setup", "the", "records", "from", "the", "selected", "resource", "that", "are", "going", "to", "be", "rendered", "if", "authorized" ]
a95b5fc894eeacd71271ccf33f05d286b5c32b9f
https://github.com/autoforce/APIcasso/blob/a95b5fc894eeacd71271ccf33f05d286b5c32b9f/app/controllers/apicasso/crud_controller.rb#L98-L106
train
autoforce/APIcasso
app/controllers/apicasso/crud_controller.rb
Apicasso.CrudController.index_json
def index_json if params[:group].present? @records.group(params[:group][:by].split(',')) .send(:calculate, params[:group][:calculate], params[:group][:field]) else collection_response end end
ruby
def index_json if params[:group].present? @records.group(params[:group][:by].split(',')) .send(:calculate, params[:group][:calculate], params[:group][:field]) else collection_response end end
[ "def", "index_json", "if", "params", "[", ":group", "]", ".", "present?", "@records", ".", "group", "(", "params", "[", ":group", "]", "[", ":by", "]", ".", "split", "(", "','", ")", ")", ".", "send", "(", ":calculate", ",", "params", "[", ":group", "]", "[", ":calculate", "]", ",", "params", "[", ":group", "]", "[", ":field", "]", ")", "else", "collection_response", "end", "end" ]
The response for index action, which can be a pagination of a record collection or a grouped count of attributes
[ "The", "response", "for", "index", "action", "which", "can", "be", "a", "pagination", "of", "a", "record", "collection", "or", "a", "grouped", "count", "of", "attributes" ]
a95b5fc894eeacd71271ccf33f05d286b5c32b9f
https://github.com/autoforce/APIcasso/blob/a95b5fc894eeacd71271ccf33f05d286b5c32b9f/app/controllers/apicasso/crud_controller.rb#L133-L142
train
autoforce/APIcasso
app/controllers/apicasso/application_controller.rb
Apicasso.ApplicationController.request_metadata
def request_metadata { uuid: request.uuid, url: request.original_url, headers: request.env.select { |key, _v| key =~ /^HTTP_/ }, ip: request.remote_ip } end
ruby
def request_metadata { uuid: request.uuid, url: request.original_url, headers: request.env.select { |key, _v| key =~ /^HTTP_/ }, ip: request.remote_ip } end
[ "def", "request_metadata", "{", "uuid", ":", "request", ".", "uuid", ",", "url", ":", "request", ".", "original_url", ",", "headers", ":", "request", ".", "env", ".", "select", "{", "|", "key", ",", "_v", "|", "key", "=~", "/", "/", "}", ",", "ip", ":", "request", ".", "remote_ip", "}", "end" ]
Information that gets inserted on `register_api_request` as auditing data about the request. Returns a Hash with UUID, URL, HTTP Headers and IP
[ "Information", "that", "gets", "inserted", "on", "register_api_request", "as", "auditing", "data", "about", "the", "request", ".", "Returns", "a", "Hash", "with", "UUID", "URL", "HTTP", "Headers", "and", "IP" ]
a95b5fc894eeacd71271ccf33f05d286b5c32b9f
https://github.com/autoforce/APIcasso/blob/a95b5fc894eeacd71271ccf33f05d286b5c32b9f/app/controllers/apicasso/application_controller.rb#L49-L56
train
autoforce/APIcasso
app/models/apicasso/ability.rb
Apicasso.Ability.build_permissions
def build_permissions(opts = {}) permission = opts[:permission].to_sym clearances = opts[:clearance] # To have full read access to the whole APIcasso just set a # true key scope operation. # Usage: # To have full read access to the system the scope would be: # => `{read: true}` if clearances == true can permission, :all else clearances.to_h.each do |klass, clearance| klass_module = klass.underscore.singularize.to_sym klass = klass.classify.constantize can permission, klass_module if clearance == true # Usage: # To have a key reading all channels and all accouts # you would have a scope: # => `{read: {channel: true, accout: true}}` can permission, klass else clear_for(permission, klass, clearance) end end end end
ruby
def build_permissions(opts = {}) permission = opts[:permission].to_sym clearances = opts[:clearance] # To have full read access to the whole APIcasso just set a # true key scope operation. # Usage: # To have full read access to the system the scope would be: # => `{read: true}` if clearances == true can permission, :all else clearances.to_h.each do |klass, clearance| klass_module = klass.underscore.singularize.to_sym klass = klass.classify.constantize can permission, klass_module if clearance == true # Usage: # To have a key reading all channels and all accouts # you would have a scope: # => `{read: {channel: true, accout: true}}` can permission, klass else clear_for(permission, klass, clearance) end end end end
[ "def", "build_permissions", "(", "opts", "=", "{", "}", ")", "permission", "=", "opts", "[", ":permission", "]", ".", "to_sym", "clearances", "=", "opts", "[", ":clearance", "]", "# To have full read access to the whole APIcasso just set a", "# true key scope operation.", "# Usage:", "# To have full read access to the system the scope would be:", "# => `{read: true}`", "if", "clearances", "==", "true", "can", "permission", ",", ":all", "else", "clearances", ".", "to_h", ".", "each", "do", "|", "klass", ",", "clearance", "|", "klass_module", "=", "klass", ".", "underscore", ".", "singularize", ".", "to_sym", "klass", "=", "klass", ".", "classify", ".", "constantize", "can", "permission", ",", "klass_module", "if", "clearance", "==", "true", "# Usage:", "# To have a key reading all channels and all accouts", "# you would have a scope:", "# => `{read: {channel: true, accout: true}}`", "can", "permission", ",", "klass", "else", "clear_for", "(", "permission", ",", "klass", ",", "clearance", ")", "end", "end", "end", "end" ]
Method that initializes CanCanCan with the scope of permissions based on current key from request @param key [Object] a key object by APIcasso to CanCanCan with ability
[ "Method", "that", "initializes", "CanCanCan", "with", "the", "scope", "of", "permissions", "based", "on", "current", "key", "from", "request" ]
a95b5fc894eeacd71271ccf33f05d286b5c32b9f
https://github.com/autoforce/APIcasso/blob/a95b5fc894eeacd71271ccf33f05d286b5c32b9f/app/models/apicasso/ability.rb#L20-L46
train
rom-rb/rom-factory
lib/rom/factory/factories.rb
ROM::Factory.Factories.define
def define(spec, **opts, &block) name, parent = spec.is_a?(Hash) ? spec.flatten(1) : spec if registry.key?(name) raise ArgumentError, "#{name.inspect} factory has been already defined" end builder = if parent extend_builder(name, registry[parent], &block) else relation_name = opts.fetch(:relation) { infer_relation(name) } relation = rom.relations[relation_name] DSL.new(name, relation: relation.struct_namespace(struct_namespace), factories: self, &block).call end registry[name] = builder end
ruby
def define(spec, **opts, &block) name, parent = spec.is_a?(Hash) ? spec.flatten(1) : spec if registry.key?(name) raise ArgumentError, "#{name.inspect} factory has been already defined" end builder = if parent extend_builder(name, registry[parent], &block) else relation_name = opts.fetch(:relation) { infer_relation(name) } relation = rom.relations[relation_name] DSL.new(name, relation: relation.struct_namespace(struct_namespace), factories: self, &block).call end registry[name] = builder end
[ "def", "define", "(", "spec", ",", "**", "opts", ",", "&", "block", ")", "name", ",", "parent", "=", "spec", ".", "is_a?", "(", "Hash", ")", "?", "spec", ".", "flatten", "(", "1", ")", ":", "spec", "if", "registry", ".", "key?", "(", "name", ")", "raise", "ArgumentError", ",", "\"#{name.inspect} factory has been already defined\"", "end", "builder", "=", "if", "parent", "extend_builder", "(", "name", ",", "registry", "[", "parent", "]", ",", "block", ")", "else", "relation_name", "=", "opts", ".", "fetch", "(", ":relation", ")", "{", "infer_relation", "(", "name", ")", "}", "relation", "=", "rom", ".", "relations", "[", "relation_name", "]", "DSL", ".", "new", "(", "name", ",", "relation", ":", "relation", ".", "struct_namespace", "(", "struct_namespace", ")", ",", "factories", ":", "self", ",", "block", ")", ".", "call", "end", "registry", "[", "name", "]", "=", "builder", "end" ]
Define a new builder @example a simple builder MyFactory.define(:user) do |f| f.name "Jane" f.email "[email protected]" end @example a builder using auto-generated fake values MyFactory.define(:user) do |f| f.name { fake(:name) } f.email { fake(:internet, :email) } end @example a builder using sequenced values MyFactory.define(:user) do |f| f.sequence(:name) { |n| "user-#{n}" } end @example a builder using values from other attribute(s) MyFactory.define(:user) do |f| f.name "Jane" f.email { |name| "#{name.downcase}@rom-rb.org" } end @example a builder with "belongs-to" association MyFactory.define(:group) do |f| f.name "Admins" end MyFactory.define(:user) do |f| f.name "Jane" f.association(:group) end @example a builder with "has-many" association MyFactory.define(:group) do |f| f.name "Admins" f.association(:users, count: 2) end MyFactory.define(:user) do |f| f.sequence(:name) { |n| "user-#{n}" } end @example a builder which extends another builder MyFactory.define(:user) do |f| f.name "Jane" f.admin false end MyFactory.define(admin: :user) do |f| f.admin true end @param [Symbol, Hash<Symbol=>Symbol>] spec Builder identifier, can point to a parent builder too @param [Hash] opts Additional options @option opts [Symbol] relation An optional relation name (defaults to pluralized builder name) @return [ROM::Factory::Builder] @api public
[ "Define", "a", "new", "builder" ]
ca7425bbc5fa0ff3ae1913d79fc84b1ef86ccf9f
https://github.com/rom-rb/rom-factory/blob/ca7425bbc5fa0ff3ae1913d79fc84b1ef86ccf9f/lib/rom/factory/factories.rb#L132-L149
train
rom-rb/rom-factory
lib/rom/factory/factories.rb
ROM::Factory.Factories.struct_namespace
def struct_namespace(namespace = Undefined) if namespace.equal?(Undefined) options[:struct_namespace] else with(struct_namespace: namespace) end end
ruby
def struct_namespace(namespace = Undefined) if namespace.equal?(Undefined) options[:struct_namespace] else with(struct_namespace: namespace) end end
[ "def", "struct_namespace", "(", "namespace", "=", "Undefined", ")", "if", "namespace", ".", "equal?", "(", "Undefined", ")", "options", "[", ":struct_namespace", "]", "else", "with", "(", "struct_namespace", ":", "namespace", ")", "end", "end" ]
Get factories with a custom struct namespace @example EntityFactory = MyFactory.struct_namespace(MyApp::Entities) EntityFactory[:user] # => #<MyApp::Entities::User id=2 ...> @param [Module] namespace @return [Factories] @api public
[ "Get", "factories", "with", "a", "custom", "struct", "namespace" ]
ca7425bbc5fa0ff3ae1913d79fc84b1ef86ccf9f
https://github.com/rom-rb/rom-factory/blob/ca7425bbc5fa0ff3ae1913d79fc84b1ef86ccf9f/lib/rom/factory/factories.rb#L191-L197
train
kylewlacy/timerizer
lib/timerizer/wall_clock.rb
Timerizer.WallClock.hour
def hour(system = :twenty_four_hour) hour = self.to_duration.to_units(:hour, :minute, :second).fetch(:hour) if system == :twelve_hour if hour == 0 12 elsif hour > 12 hour - 12 else hour end elsif (system == :twenty_four_hour) hour else raise ArgumentError, "system should be :twelve_hour or :twenty_four_hour" end end
ruby
def hour(system = :twenty_four_hour) hour = self.to_duration.to_units(:hour, :minute, :second).fetch(:hour) if system == :twelve_hour if hour == 0 12 elsif hour > 12 hour - 12 else hour end elsif (system == :twenty_four_hour) hour else raise ArgumentError, "system should be :twelve_hour or :twenty_four_hour" end end
[ "def", "hour", "(", "system", "=", ":twenty_four_hour", ")", "hour", "=", "self", ".", "to_duration", ".", "to_units", "(", ":hour", ",", ":minute", ",", ":second", ")", ".", "fetch", "(", ":hour", ")", "if", "system", "==", ":twelve_hour", "if", "hour", "==", "0", "12", "elsif", "hour", ">", "12", "hour", "-", "12", "else", "hour", "end", "elsif", "(", "system", "==", ":twenty_four_hour", ")", "hour", "else", "raise", "ArgumentError", ",", "\"system should be :twelve_hour or :twenty_four_hour\"", "end", "end" ]
Get the hour of the WallClock. @param [Symbol] system The houring system to use (either `:twelve_hour` or `:twenty_four_hour`; default `:twenty_four_hour`) @return [Integer] The hour component of the WallClock
[ "Get", "the", "hour", "of", "the", "WallClock", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/wall_clock.rb#L136-L151
train
kylewlacy/timerizer
lib/timerizer/duration.rb
Timerizer.Duration.after
def after(time) time = time.to_time prev_day = time.mday prev_month = time.month prev_year = time.year units = self.to_units(:years, :months, :days, :seconds) date_in_month = self.class.build_date( prev_year + units[:years], prev_month + units[:months], prev_day ) date = date_in_month + units[:days] Time.new( date.year, date.month, date.day, time.hour, time.min, time.sec ) + units[:seconds] end
ruby
def after(time) time = time.to_time prev_day = time.mday prev_month = time.month prev_year = time.year units = self.to_units(:years, :months, :days, :seconds) date_in_month = self.class.build_date( prev_year + units[:years], prev_month + units[:months], prev_day ) date = date_in_month + units[:days] Time.new( date.year, date.month, date.day, time.hour, time.min, time.sec ) + units[:seconds] end
[ "def", "after", "(", "time", ")", "time", "=", "time", ".", "to_time", "prev_day", "=", "time", ".", "mday", "prev_month", "=", "time", ".", "month", "prev_year", "=", "time", ".", "year", "units", "=", "self", ".", "to_units", "(", ":years", ",", ":months", ",", ":days", ",", ":seconds", ")", "date_in_month", "=", "self", ".", "class", ".", "build_date", "(", "prev_year", "+", "units", "[", ":years", "]", ",", "prev_month", "+", "units", "[", ":months", "]", ",", "prev_day", ")", "date", "=", "date_in_month", "+", "units", "[", ":days", "]", "Time", ".", "new", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ",", "time", ".", "hour", ",", "time", ".", "min", ",", "time", ".", "sec", ")", "+", "units", "[", ":seconds", "]", "end" ]
Returns the time `self` later than the given time. @param [Time] time The initial time. @return [Time] The time after this {Duration} has elapsed past the given time. @example 5 minutes after January 1st, 2000 at noon 5.minutes.after(Time.new(2000, 1, 1, 12, 00, 00)) # => 2000-01-01 12:05:00 -0800 @see #ago @see #before @see #from_now
[ "Returns", "the", "time", "self", "later", "than", "the", "given", "time", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/duration.rb#L234-L258
train
kylewlacy/timerizer
lib/timerizer/duration.rb
Timerizer.Duration.to_unit
def to_unit(unit) unit_details = self.class.resolve_unit(unit) if unit_details.has_key?(:seconds) seconds = self.normalize.get(:seconds) self.class.div(seconds, unit_details.fetch(:seconds)) elsif unit_details.has_key?(:months) months = self.denormalize.get(:months) self.class.div(months, unit_details.fetch(:months)) else raise "Unit should have key :seconds or :months" end end
ruby
def to_unit(unit) unit_details = self.class.resolve_unit(unit) if unit_details.has_key?(:seconds) seconds = self.normalize.get(:seconds) self.class.div(seconds, unit_details.fetch(:seconds)) elsif unit_details.has_key?(:months) months = self.denormalize.get(:months) self.class.div(months, unit_details.fetch(:months)) else raise "Unit should have key :seconds or :months" end end
[ "def", "to_unit", "(", "unit", ")", "unit_details", "=", "self", ".", "class", ".", "resolve_unit", "(", "unit", ")", "if", "unit_details", ".", "has_key?", "(", ":seconds", ")", "seconds", "=", "self", ".", "normalize", ".", "get", "(", ":seconds", ")", "self", ".", "class", ".", "div", "(", "seconds", ",", "unit_details", ".", "fetch", "(", ":seconds", ")", ")", "elsif", "unit_details", ".", "has_key?", "(", ":months", ")", "months", "=", "self", ".", "denormalize", ".", "get", "(", ":months", ")", "self", ".", "class", ".", "div", "(", "months", ",", "unit_details", ".", "fetch", "(", ":months", ")", ")", "else", "raise", "\"Unit should have key :seconds or :months\"", "end", "end" ]
Convert the duration to a given unit. @param [Symbol] unit The unit to convert to. See {UNIT_ALIASES} for a list of valid unit names. @return [Integer] The quantity of the given unit present in `self`. Note that, if `self` cannot be represented exactly by `unit`, then the result will be truncated (rounded toward 0 instead of rounding down, unlike normal Ruby integer division). @raise ArgumentError if the given unit could not be resolved. @example 1.hour.to_unit(:minutes) # => 60 121.seconds.to_unit(:minutes) # => 2 @note The duration is normalized or denormalized first, depending on the unit requested. This means that, by default, the returned unit will be an approximation if it cannot be represented exactly by the duration, such as when converting a duration of months to seconds, or vice versa. @see #to_units
[ "Convert", "the", "duration", "to", "a", "given", "unit", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/duration.rb#L293-L305
train
kylewlacy/timerizer
lib/timerizer/duration.rb
Timerizer.Duration.-
def -(other) case other when 0 self when Duration Duration.new( seconds: @seconds - other.get(:seconds), months: @months - other.get(:months) ) else raise ArgumentError, "Cannot subtract #{other.inspect} from Duration #{self}" end end
ruby
def -(other) case other when 0 self when Duration Duration.new( seconds: @seconds - other.get(:seconds), months: @months - other.get(:months) ) else raise ArgumentError, "Cannot subtract #{other.inspect} from Duration #{self}" end end
[ "def", "-", "(", "other", ")", "case", "other", "when", "0", "self", "when", "Duration", "Duration", ".", "new", "(", "seconds", ":", "@seconds", "-", "other", ".", "get", "(", ":seconds", ")", ",", "months", ":", "@months", "-", "other", ".", "get", "(", ":months", ")", ")", "else", "raise", "ArgumentError", ",", "\"Cannot subtract #{other.inspect} from Duration #{self}\"", "end", "end" ]
Subtract two durations. @param [Duration] other The duration to subtract. @return [Duration] The resulting duration with each component subtracted from the input duration. @example 1.day - 1.hour == 23.hours
[ "Subtract", "two", "durations", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/duration.rb#L504-L516
train
kylewlacy/timerizer
lib/timerizer/duration.rb
Timerizer.Duration.*
def *(other) case other when Integer Duration.new( seconds: @seconds * other, months: @months * other ) else raise ArgumentError, "Cannot multiply Duration #{self} by #{other.inspect}" end end
ruby
def *(other) case other when Integer Duration.new( seconds: @seconds * other, months: @months * other ) else raise ArgumentError, "Cannot multiply Duration #{self} by #{other.inspect}" end end
[ "def", "*", "(", "other", ")", "case", "other", "when", "Integer", "Duration", ".", "new", "(", "seconds", ":", "@seconds", "*", "other", ",", "months", ":", "@months", "*", "other", ")", "else", "raise", "ArgumentError", ",", "\"Cannot multiply Duration #{self} by #{other.inspect}\"", "end", "end" ]
Multiply a duration by a scalar. @param [Integer] other The scalar to multiply by. @return [Duration] The resulting duration with each component multiplied by the scalar. @example 1.day * 7 == 1.week
[ "Multiply", "a", "duration", "by", "a", "scalar", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/duration.rb#L527-L537
train
kylewlacy/timerizer
lib/timerizer/duration.rb
Timerizer.Duration.to_s
def to_s(format = :long, options = nil) format = case format when Symbol FORMATS.fetch(format) when Hash FORMATS.fetch(:long).merge(format) else raise ArgumentError, "Expected #{format.inspect} to be a Symbol or Hash" end format = format.merge(options || {}) count = if format[:count].nil? || format[:count] == :all UNITS.count else format[:count] end format_units = format.fetch(:units) units = self.to_units(*format_units.keys).select {|unit, n| n > 0} if units.empty? units = {seconds: 0} end separator = format[:separator] || ' ' delimiter = format[:delimiter] || ', ' units.take(count).map do |unit, n| unit_label = format_units.fetch(unit) singular, plural = case unit_label when Array unit_label else [unit_label, unit_label] end unit_name = if n == 1 singular else plural || singular end [n, unit_name].join(separator) end.join(format[:delimiter] || ', ') end
ruby
def to_s(format = :long, options = nil) format = case format when Symbol FORMATS.fetch(format) when Hash FORMATS.fetch(:long).merge(format) else raise ArgumentError, "Expected #{format.inspect} to be a Symbol or Hash" end format = format.merge(options || {}) count = if format[:count].nil? || format[:count] == :all UNITS.count else format[:count] end format_units = format.fetch(:units) units = self.to_units(*format_units.keys).select {|unit, n| n > 0} if units.empty? units = {seconds: 0} end separator = format[:separator] || ' ' delimiter = format[:delimiter] || ', ' units.take(count).map do |unit, n| unit_label = format_units.fetch(unit) singular, plural = case unit_label when Array unit_label else [unit_label, unit_label] end unit_name = if n == 1 singular else plural || singular end [n, unit_name].join(separator) end.join(format[:delimiter] || ', ') end
[ "def", "to_s", "(", "format", "=", ":long", ",", "options", "=", "nil", ")", "format", "=", "case", "format", "when", "Symbol", "FORMATS", ".", "fetch", "(", "format", ")", "when", "Hash", "FORMATS", ".", "fetch", "(", ":long", ")", ".", "merge", "(", "format", ")", "else", "raise", "ArgumentError", ",", "\"Expected #{format.inspect} to be a Symbol or Hash\"", "end", "format", "=", "format", ".", "merge", "(", "options", "||", "{", "}", ")", "count", "=", "if", "format", "[", ":count", "]", ".", "nil?", "||", "format", "[", ":count", "]", "==", ":all", "UNITS", ".", "count", "else", "format", "[", ":count", "]", "end", "format_units", "=", "format", ".", "fetch", "(", ":units", ")", "units", "=", "self", ".", "to_units", "(", "format_units", ".", "keys", ")", ".", "select", "{", "|", "unit", ",", "n", "|", "n", ">", "0", "}", "if", "units", ".", "empty?", "units", "=", "{", "seconds", ":", "0", "}", "end", "separator", "=", "format", "[", ":separator", "]", "||", "' '", "delimiter", "=", "format", "[", ":delimiter", "]", "||", "', '", "units", ".", "take", "(", "count", ")", ".", "map", "do", "|", "unit", ",", "n", "|", "unit_label", "=", "format_units", ".", "fetch", "(", "unit", ")", "singular", ",", "plural", "=", "case", "unit_label", "when", "Array", "unit_label", "else", "[", "unit_label", ",", "unit_label", "]", "end", "unit_name", "=", "if", "n", "==", "1", "singular", "else", "plural", "||", "singular", "end", "[", "n", ",", "unit_name", "]", ".", "join", "(", "separator", ")", "end", ".", "join", "(", "format", "[", ":delimiter", "]", "||", "', '", ")", "end" ]
Convert a duration to a human-readable string. @param [Symbol, Hash] format The format type to format the duration with. `format` can either be a key from the {FORMATS} hash or a hash with the same shape as `options`. @param [Hash, nil] options Additional options to use to override default format options. @option options [Hash<Symbol, String>] :units The full list of unit names to use. Keys are unit names (see {UNIT_ALIASES} for a full list) and values are strings to use when converting that unit to a string. Values can also be an array, where the first item of the array will be used for singular unit names and the second item will be used for plural unit names. Note that this option will completely override the input formats' list of names, so all units that should be used must be specified! @option options [String] :separator The separator to use between a unit quantity and the unit's name. For example, the string `"1 second"` uses a separator of `" "`. @option options [String] :delimiter The delimiter to use between separate units. For example, the string `"1 minute, 1 second"` uses a separator of `", "` @option options [Integer, nil, :all] :count The number of significant units to use in the string, or `nil` / `:all` to use all units. For example, if the given duration is `1.day 1.week 1.month`, and `options[:count]` is 2, then the resulting string will only include the month and the week components of the string. @return [String] The duration formatted as a string.
[ "Convert", "a", "duration", "to", "a", "human", "-", "readable", "string", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/duration.rb#L606-L654
train
kylewlacy/timerizer
lib/timerizer/duration.rb
Timerizer.Duration.to_rounded_s
def to_rounded_s(format = :min_long, options = nil) format = case format when Symbol FORMATS.fetch(format) when Hash FORMATS.fetch(:long).merge(format) else raise ArgumentError, "Expected #{format.inspect} to be a Symbol or Hash" end format = format.merge(Hash(options)) places = format[:count] begin places = Integer(places) # raise if nil or `:all` supplied as value rescue TypeError places = 2 end q = RoundedTime.call(self, places) q.to_s(format, options) end
ruby
def to_rounded_s(format = :min_long, options = nil) format = case format when Symbol FORMATS.fetch(format) when Hash FORMATS.fetch(:long).merge(format) else raise ArgumentError, "Expected #{format.inspect} to be a Symbol or Hash" end format = format.merge(Hash(options)) places = format[:count] begin places = Integer(places) # raise if nil or `:all` supplied as value rescue TypeError places = 2 end q = RoundedTime.call(self, places) q.to_s(format, options) end
[ "def", "to_rounded_s", "(", "format", "=", ":min_long", ",", "options", "=", "nil", ")", "format", "=", "case", "format", "when", "Symbol", "FORMATS", ".", "fetch", "(", "format", ")", "when", "Hash", "FORMATS", ".", "fetch", "(", ":long", ")", ".", "merge", "(", "format", ")", "else", "raise", "ArgumentError", ",", "\"Expected #{format.inspect} to be a Symbol or Hash\"", "end", "format", "=", "format", ".", "merge", "(", "Hash", "(", "options", ")", ")", "places", "=", "format", "[", ":count", "]", "begin", "places", "=", "Integer", "(", "places", ")", "# raise if nil or `:all` supplied as value", "rescue", "TypeError", "places", "=", "2", "end", "q", "=", "RoundedTime", ".", "call", "(", "self", ",", "places", ")", "q", ".", "to_s", "(", "format", ",", "options", ")", "end" ]
Convert a Duration to a human-readable string using a rounded value. By 'rounded', we mean that the resulting value is rounded up if the input includes a value of more than half of one of the least-significant unit to be returned. For example, `(17.hours 43.minutes 31.seconds)`, when rounded to two units (hours and minutes), would return "17 hours, 44 minutes". By contrast, `#to_s`, with a `:count` option of 2, would return a value of "17 hours, 43 minutes": truncating, rather than rounding. Note that this method overloads the meaning of the `:count` option value as documented below. If the passed-in option value is numeric, it will be honored, and rounding will take place to that number of units. If the value is either `:all` or the default `nil`, then _rounding_ will be done to two units, and the rounded value will be passed on to `#to_s` with the options specified (which will result in a maximum of two time units being output). @param [Symbol, Hash] format The format type to format the duration with. `format` can either be a key from the {FORMATS} hash or a hash with the same shape as `options`. The default is `:min_long`, which strongly resembles `:long` with the omission of `:weeks` units and a default `:count` of 2. @param [Hash, nil] options Additional options to use to override default format options. @option options [Hash<Symbol, String>] :units The full list of unit names to use. Keys are unit names (see {UNIT_ALIASES} for a full list) and values are strings to use when converting that unit to a string. Values can also be an array, where the first item of the array will be used for singular unit names and the second item will be used for plural unit names. Note that this option will completely override the input formats' list of names, so all units that should be used must be specified! @option options [String] :separator The separator to use between a unit quantity and the unit's name. For example, the string `"1 second"` uses a separator of `" "`. @option options [String] :delimiter The delimiter to use between separate units. For example, the string `"1 minute, 1 second"` uses a separator of `", "` @option options [Integer, nil, :all] :count The number of significant units to use in the string, or `nil` / `:all` to use all units. For example, if the given duration is `1.day 1.week 1.month`, and `options[:count]` is 2, then the resulting string will only include the month and the week components of the string. @return [String] The rounded duration formatted as a string.
[ "Convert", "a", "Duration", "to", "a", "human", "-", "readable", "string", "using", "a", "rounded", "value", "." ]
3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8
https://github.com/kylewlacy/timerizer/blob/3d9949ad95d167e40a7b9b1f8b9d0817cdace4c8/lib/timerizer/duration.rb#L702-L722
train
github/elastomer-client
lib/elastomer/client/rest_api_spec/api_spec.rb
Elastomer::Client::RestApiSpec.ApiSpec.select_params
def select_params(api:, from:) rest_api = get(api) return from if rest_api.nil? rest_api.select_params(from: from) end
ruby
def select_params(api:, from:) rest_api = get(api) return from if rest_api.nil? rest_api.select_params(from: from) end
[ "def", "select_params", "(", "api", ":", ",", "from", ":", ")", "rest_api", "=", "get", "(", "api", ")", "return", "from", "if", "rest_api", ".", "nil?", "rest_api", ".", "select_params", "(", "from", ":", "from", ")", "end" ]
Given an API descriptor name and a set of request parameters, select those params that are accepted by the API endpoint. api - the api descriptor name as a String from - the Hash containing the request params Returns a new Hash containing the valid params for the api
[ "Given", "an", "API", "descriptor", "name", "and", "a", "set", "of", "request", "parameters", "select", "those", "params", "that", "are", "accepted", "by", "the", "API", "endpoint", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/rest_api_spec/api_spec.rb#L26-L30
train
github/elastomer-client
lib/elastomer/client/rest_api_spec/api_spec.rb
Elastomer::Client::RestApiSpec.ApiSpec.valid_param?
def valid_param?(api:, param:) rest_api = get(api) return true if rest_api.nil? rest_api.valid_param?(param) end
ruby
def valid_param?(api:, param:) rest_api = get(api) return true if rest_api.nil? rest_api.valid_param?(param) end
[ "def", "valid_param?", "(", "api", ":", ",", "param", ":", ")", "rest_api", "=", "get", "(", "api", ")", "return", "true", "if", "rest_api", ".", "nil?", "rest_api", ".", "valid_param?", "(", "param", ")", "end" ]
Given an API descriptor name and a single request parameter, returns `true` if the parameter is valid for the given API. This method always returns `true` if the API is unknown. api - the api descriptor name as a String param - the request parameter name as a String Returns `true` if the param is valid for the API.
[ "Given", "an", "API", "descriptor", "name", "and", "a", "single", "request", "parameter", "returns", "true", "if", "the", "parameter", "is", "valid", "for", "the", "given", "API", ".", "This", "method", "always", "returns", "true", "if", "the", "API", "is", "unknown", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/rest_api_spec/api_spec.rb#L40-L44
train
github/elastomer-client
lib/elastomer/client/rest_api_spec/api_spec.rb
Elastomer::Client::RestApiSpec.ApiSpec.select_parts
def select_parts(api:, from:) rest_api = get(api) return from if rest_api.nil? rest_api.select_parts(from: from) end
ruby
def select_parts(api:, from:) rest_api = get(api) return from if rest_api.nil? rest_api.select_parts(from: from) end
[ "def", "select_parts", "(", "api", ":", ",", "from", ":", ")", "rest_api", "=", "get", "(", "api", ")", "return", "from", "if", "rest_api", ".", "nil?", "rest_api", ".", "select_parts", "(", "from", ":", "from", ")", "end" ]
Given an API descriptor name and a set of request path parts, select those parts that are accepted by the API endpoint. api - the api descriptor name as a String from - the Hash containing the path parts Returns a new Hash containing the valid path parts for the api
[ "Given", "an", "API", "descriptor", "name", "and", "a", "set", "of", "request", "path", "parts", "select", "those", "parts", "that", "are", "accepted", "by", "the", "API", "endpoint", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/rest_api_spec/api_spec.rb#L53-L57
train
github/elastomer-client
lib/elastomer/client/rest_api_spec/api_spec.rb
Elastomer::Client::RestApiSpec.ApiSpec.valid_part?
def valid_part?(api:, part:) rest_api = get(api) return true if rest_api.nil? rest_api.valid_part?(part) end
ruby
def valid_part?(api:, part:) rest_api = get(api) return true if rest_api.nil? rest_api.valid_part?(part) end
[ "def", "valid_part?", "(", "api", ":", ",", "part", ":", ")", "rest_api", "=", "get", "(", "api", ")", "return", "true", "if", "rest_api", ".", "nil?", "rest_api", ".", "valid_part?", "(", "part", ")", "end" ]
Given an API descriptor name and a single path part, returns `true` if the path part is valid for the given API. This method always returns `true` if the API is unknown. api - the api descriptor name as a String part - the path part name as a String Returns `true` if the path part is valid for the API.
[ "Given", "an", "API", "descriptor", "name", "and", "a", "single", "path", "part", "returns", "true", "if", "the", "path", "part", "is", "valid", "for", "the", "given", "API", ".", "This", "method", "always", "returns", "true", "if", "the", "API", "is", "unknown", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/rest_api_spec/api_spec.rb#L67-L71
train
github/elastomer-client
lib/elastomer/client/rest_api_spec/api_spec.rb
Elastomer::Client::RestApiSpec.ApiSpec.select_common_params
def select_common_params(from:) return from if @common_params.empty? from.select {|k,v| valid_common_param?(k)} end
ruby
def select_common_params(from:) return from if @common_params.empty? from.select {|k,v| valid_common_param?(k)} end
[ "def", "select_common_params", "(", "from", ":", ")", "return", "from", "if", "@common_params", ".", "empty?", "from", ".", "select", "{", "|", "k", ",", "v", "|", "valid_common_param?", "(", "k", ")", "}", "end" ]
Select the common request parameters from the given params. from - the Hash containing the request params Returns a new Hash containing the valid common request params
[ "Select", "the", "common", "request", "parameters", "from", "the", "given", "params", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/rest_api_spec/api_spec.rb#L78-L81
train
github/elastomer-client
lib/elastomer/client/rest_api_spec/api_spec.rb
Elastomer::Client::RestApiSpec.ApiSpec.validate_params!
def validate_params!(api:, params:) rest_api = get(api) return params if rest_api.nil? params.keys.each do |key| unless rest_api.valid_param?(key) || valid_common_param?(key) raise ::Elastomer::Client::IllegalArgument, "'#{key}' is not a valid parameter for the '#{api}' API" end end params end
ruby
def validate_params!(api:, params:) rest_api = get(api) return params if rest_api.nil? params.keys.each do |key| unless rest_api.valid_param?(key) || valid_common_param?(key) raise ::Elastomer::Client::IllegalArgument, "'#{key}' is not a valid parameter for the '#{api}' API" end end params end
[ "def", "validate_params!", "(", "api", ":", ",", "params", ":", ")", "rest_api", "=", "get", "(", "api", ")", "return", "params", "if", "rest_api", ".", "nil?", "params", ".", "keys", ".", "each", "do", "|", "key", "|", "unless", "rest_api", ".", "valid_param?", "(", "key", ")", "||", "valid_common_param?", "(", "key", ")", "raise", "::", "Elastomer", "::", "Client", "::", "IllegalArgument", ",", "\"'#{key}' is not a valid parameter for the '#{api}' API\"", "end", "end", "params", "end" ]
Given an API descriptor name and a set of request parameters, ensure that all the request parameters are valid for the API endpoint. If an invalid parameter is found then an IllegalArgument exception is raised. api - the api descriptor name as a String from - the Hash containing the request params Returns the params unmodified Raises an IllegalArgument exception if an invalid parameter is found.
[ "Given", "an", "API", "descriptor", "name", "and", "a", "set", "of", "request", "parameters", "ensure", "that", "all", "the", "request", "parameters", "are", "valid", "for", "the", "API", "endpoint", ".", "If", "an", "invalid", "parameter", "is", "found", "then", "an", "IllegalArgument", "exception", "is", "raised", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/rest_api_spec/api_spec.rb#L97-L107
train
github/elastomer-client
lib/elastomer/client/multi_search.rb
Elastomer.Client.multi_search
def multi_search(body = nil, params = nil) if block_given? params, body = (body || {}), nil yield msearch_obj = MultiSearch.new(self, params) msearch_obj.call else raise "multi_search request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_msearch", params.merge(body: body, action: "msearch", rest_api: "msearch") response.body end end
ruby
def multi_search(body = nil, params = nil) if block_given? params, body = (body || {}), nil yield msearch_obj = MultiSearch.new(self, params) msearch_obj.call else raise "multi_search request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_msearch", params.merge(body: body, action: "msearch", rest_api: "msearch") response.body end end
[ "def", "multi_search", "(", "body", "=", "nil", ",", "params", "=", "nil", ")", "if", "block_given?", "params", ",", "body", "=", "(", "body", "||", "{", "}", ")", ",", "nil", "yield", "msearch_obj", "=", "MultiSearch", ".", "new", "(", "self", ",", "params", ")", "msearch_obj", ".", "call", "else", "raise", "\"multi_search request body cannot be nil\"", "if", "body", ".", "nil?", "params", "||=", "{", "}", "response", "=", "self", ".", "post", "\"{/index}{/type}/_msearch\"", ",", "params", ".", "merge", "(", "body", ":", "body", ",", "action", ":", "\"msearch\"", ",", "rest_api", ":", "\"msearch\"", ")", "response", ".", "body", "end", "end" ]
Execute an array of searches in bulk. Results are returned in an array in the order the queries were sent. The `multi_search` method can be used in two ways. Without a block the method will perform an API call, and it requires a bulk request body and optional request parameters. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html body - Request body as a String (required if a block is not given) params - Optional request parameters as a Hash block - Passed to a MultiSearch instance which assembles the searches into a single request. Examples # index and type in request body multi_search(request_body) # index in URI multi_search(request_body, index: 'default-index') # block form multi_search(index: 'default-index') do |m| m.search({query: {match_all: {}}, size: 0) m.search({query: {field: {"foo" => "bar"}}}, type: 'default-type') ... end Returns the response body as a Hash
[ "Execute", "an", "array", "of", "searches", "in", "bulk", ".", "Results", "are", "returned", "in", "an", "array", "in", "the", "order", "the", "queries", "were", "sent", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/multi_search.rb#L34-L46
train
github/elastomer-client
lib/elastomer/client/multi_percolate.rb
Elastomer.Client.multi_percolate
def multi_percolate(body = nil, params = nil) if block_given? params, body = (body || {}), nil yield mpercolate_obj = MultiPercolate.new(self, params) mpercolate_obj.call else raise "multi_percolate request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_mpercolate", params.merge(body: body, action: "mpercolate", rest_api: "mpercolate") response.body end end
ruby
def multi_percolate(body = nil, params = nil) if block_given? params, body = (body || {}), nil yield mpercolate_obj = MultiPercolate.new(self, params) mpercolate_obj.call else raise "multi_percolate request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_mpercolate", params.merge(body: body, action: "mpercolate", rest_api: "mpercolate") response.body end end
[ "def", "multi_percolate", "(", "body", "=", "nil", ",", "params", "=", "nil", ")", "if", "block_given?", "params", ",", "body", "=", "(", "body", "||", "{", "}", ")", ",", "nil", "yield", "mpercolate_obj", "=", "MultiPercolate", ".", "new", "(", "self", ",", "params", ")", "mpercolate_obj", ".", "call", "else", "raise", "\"multi_percolate request body cannot be nil\"", "if", "body", ".", "nil?", "params", "||=", "{", "}", "response", "=", "self", ".", "post", "\"{/index}{/type}/_mpercolate\"", ",", "params", ".", "merge", "(", "body", ":", "body", ",", "action", ":", "\"mpercolate\"", ",", "rest_api", ":", "\"mpercolate\"", ")", "response", ".", "body", "end", "end" ]
Execute an array of percolate actions in bulk. Results are returned in an array in the order the actions were sent. The `multi_percolate` method can be used in two ways. Without a block the method will perform an API call, and it requires a bulk request body and optional request parameters. See https://www.elastic.co/guide/en/elasticsearch/reference/current/search-percolate.html#_multi_percolate_api body - Request body as a String (required if a block is not given) params - Optional request parameters as a Hash block - Passed to a MultiPercolate instance which assembles the percolate actions into a single request. Examples # index and type in request body multi_percolate(request_body) # index in URI multi_percolate(request_body, index: 'default-index') # block form multi_percolate(index: 'default-index') do |m| m.percolate({ author: "pea53" }, { type: 'default-type' }) m.count({ author: "pea53" }, { type: 'type2' }) ... end Returns the response body as a Hash
[ "Execute", "an", "array", "of", "percolate", "actions", "in", "bulk", ".", "Results", "are", "returned", "in", "an", "array", "in", "the", "order", "the", "actions", "were", "sent", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/multi_percolate.rb#L34-L46
train
github/elastomer-client
lib/elastomer/client/bulk.rb
Elastomer.Client.bulk
def bulk( body = nil, params = nil ) if block_given? params, body = (body || {}), nil yield bulk_obj = Bulk.new(self, params) bulk_obj.call else raise "bulk request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_bulk", params.merge(body: body, action: "bulk", rest_api: "bulk") response.body end end
ruby
def bulk( body = nil, params = nil ) if block_given? params, body = (body || {}), nil yield bulk_obj = Bulk.new(self, params) bulk_obj.call else raise "bulk request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_bulk", params.merge(body: body, action: "bulk", rest_api: "bulk") response.body end end
[ "def", "bulk", "(", "body", "=", "nil", ",", "params", "=", "nil", ")", "if", "block_given?", "params", ",", "body", "=", "(", "body", "||", "{", "}", ")", ",", "nil", "yield", "bulk_obj", "=", "Bulk", ".", "new", "(", "self", ",", "params", ")", "bulk_obj", ".", "call", "else", "raise", "\"bulk request body cannot be nil\"", "if", "body", ".", "nil?", "params", "||=", "{", "}", "response", "=", "self", ".", "post", "\"{/index}{/type}/_bulk\"", ",", "params", ".", "merge", "(", "body", ":", "body", ",", "action", ":", "\"bulk\"", ",", "rest_api", ":", "\"bulk\"", ")", "response", ".", "body", "end", "end" ]
The `bulk` method can be used in two ways. Without a block the method will perform an API call, and it requires a bulk request body and optional request parameters. If given a block, the method will use a Bulk instance to assemble the operations called in the block into a bulk request and dispatch it at the end of the block. See https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html body - Request body as a String (required if a block is _not_ given) params - Optional request parameters as a Hash :request_size - Optional maximum request size in bytes :action_count - Optional maximum action size block - Passed to a Bulk instance which assembles the operations into one or more bulk requests. Examples bulk(request_body, :index => 'default-index') bulk(:index => 'default-index') do |b| b.index(document1) b.index(document2, :_type => 'default-type') b.delete(document3) ... end Returns the response body as a Hash
[ "The", "bulk", "method", "can", "be", "used", "in", "two", "ways", ".", "Without", "a", "block", "the", "method", "will", "perform", "an", "API", "call", "and", "it", "requires", "a", "bulk", "request", "body", "and", "optional", "request", "parameters", ".", "If", "given", "a", "block", "the", "method", "will", "use", "a", "Bulk", "instance", "to", "assemble", "the", "operations", "called", "in", "the", "block", "into", "a", "bulk", "request", "and", "dispatch", "it", "at", "the", "end", "of", "the", "block", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/bulk.rb#L31-L44
train
github/elastomer-client
lib/elastomer/client/bulk.rb
Elastomer.Client.bulk_stream_responses
def bulk_stream_responses(ops, params = {}) bulk_obj = Bulk.new(self, params) Enumerator.new do |yielder| ops.each do |action, *args| response = bulk_obj.send(action, *args) yielder.yield response unless response.nil? end response = bulk_obj.call yielder.yield response unless response.nil? end end
ruby
def bulk_stream_responses(ops, params = {}) bulk_obj = Bulk.new(self, params) Enumerator.new do |yielder| ops.each do |action, *args| response = bulk_obj.send(action, *args) yielder.yield response unless response.nil? end response = bulk_obj.call yielder.yield response unless response.nil? end end
[ "def", "bulk_stream_responses", "(", "ops", ",", "params", "=", "{", "}", ")", "bulk_obj", "=", "Bulk", ".", "new", "(", "self", ",", "params", ")", "Enumerator", ".", "new", "do", "|", "yielder", "|", "ops", ".", "each", "do", "|", "action", ",", "*", "args", "|", "response", "=", "bulk_obj", ".", "send", "(", "action", ",", "args", ")", "yielder", ".", "yield", "response", "unless", "response", ".", "nil?", "end", "response", "=", "bulk_obj", ".", "call", "yielder", ".", "yield", "response", "unless", "response", ".", "nil?", "end", "end" ]
Stream bulk actions from an Enumerator. Examples ops = [ [:index, document1, {:_type => "foo", :_id => 1}], [:create, document2], [:delete, {:_type => "bar", :_id => 42}] ] bulk_stream_responses(ops, :index => 'default-index').each do |response| puts response end Returns an Enumerator of responses.
[ "Stream", "bulk", "actions", "from", "an", "Enumerator", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/bulk.rb#L60-L72
train
github/elastomer-client
lib/elastomer/client/bulk.rb
Elastomer.Client.bulk_stream_items
def bulk_stream_items(ops, params = {}) stats = { "took" => 0, "errors" => false, "success" => 0, "failure" => 0 } bulk_stream_responses(ops, params).each do |response| stats["took"] += response["took"] stats["errors"] |= response["errors"] response["items"].each do |item| if is_ok?(item) stats["success"] += 1 else stats["failure"] += 1 end yield item end end stats end
ruby
def bulk_stream_items(ops, params = {}) stats = { "took" => 0, "errors" => false, "success" => 0, "failure" => 0 } bulk_stream_responses(ops, params).each do |response| stats["took"] += response["took"] stats["errors"] |= response["errors"] response["items"].each do |item| if is_ok?(item) stats["success"] += 1 else stats["failure"] += 1 end yield item end end stats end
[ "def", "bulk_stream_items", "(", "ops", ",", "params", "=", "{", "}", ")", "stats", "=", "{", "\"took\"", "=>", "0", ",", "\"errors\"", "=>", "false", ",", "\"success\"", "=>", "0", ",", "\"failure\"", "=>", "0", "}", "bulk_stream_responses", "(", "ops", ",", "params", ")", ".", "each", "do", "|", "response", "|", "stats", "[", "\"took\"", "]", "+=", "response", "[", "\"took\"", "]", "stats", "[", "\"errors\"", "]", "|=", "response", "[", "\"errors\"", "]", "response", "[", "\"items\"", "]", ".", "each", "do", "|", "item", "|", "if", "is_ok?", "(", "item", ")", "stats", "[", "\"success\"", "]", "+=", "1", "else", "stats", "[", "\"failure\"", "]", "+=", "1", "end", "yield", "item", "end", "end", "stats", "end" ]
Stream bulk actions from an Enumerator and passes the response items to the given block. Examples ops = [ [:index, document1, {:_type => "foo", :_id => 1}], [:create, document2], [:delete, {:_type => "bar", :_id => 42}] ] bulk_stream_items(ops, :index => 'default-index') do |item| puts item end # return value: # { # "took" => 256, # "errors" => false, # "success" => 3, # "failure" => 0 # } # sample response item: # { # "delete": { # "_index": "foo", # "_type": "bar", # "_id": "42", # "_version": 3, # "status": 200, # "found": true # } # } Returns a Hash of stats about items from the responses.
[ "Stream", "bulk", "actions", "from", "an", "Enumerator", "and", "passes", "the", "response", "items", "to", "the", "given", "block", "." ]
b02aa42f23df9776443449d44c176f1dcea5e08d
https://github.com/github/elastomer-client/blob/b02aa42f23df9776443449d44c176f1dcea5e08d/lib/elastomer/client/bulk.rb#L119-L142
train
mdsol/representors
lib/representors/representor.rb
Representors.Representor.identifier
def identifier @identifier ||= begin uri = @representor_hash.href || self.object_id protocol = @representor_hash.protocol || (uri == self.object_id ? UNKNOWN_PROTOCOL : DEFAULT_PROTOCOL) PROTOCOL_TEMPLATE % [protocol, uri] end end
ruby
def identifier @identifier ||= begin uri = @representor_hash.href || self.object_id protocol = @representor_hash.protocol || (uri == self.object_id ? UNKNOWN_PROTOCOL : DEFAULT_PROTOCOL) PROTOCOL_TEMPLATE % [protocol, uri] end end
[ "def", "identifier", "@identifier", "||=", "begin", "uri", "=", "@representor_hash", ".", "href", "||", "self", ".", "object_id", "protocol", "=", "@representor_hash", ".", "protocol", "||", "(", "uri", "==", "self", ".", "object_id", "?", "UNKNOWN_PROTOCOL", ":", "DEFAULT_PROTOCOL", ")", "PROTOCOL_TEMPLATE", "%", "[", "protocol", ",", "uri", "]", "end", "end" ]
The URI for the object @note If the URI can't be made from the provided information it constructs one from the Ruby ID @return [String]
[ "The", "URI", "for", "the", "object" ]
319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee
https://github.com/mdsol/representors/blob/319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee/lib/representors/representor.rb#L54-L60
train
mdsol/representors
lib/representor_support/utilities.rb
RepresentorSupport.Utilities.symbolize_keys
def symbolize_keys(hash) Hash[hash.map{|(k,v)| [k.to_sym,v]}] end
ruby
def symbolize_keys(hash) Hash[hash.map{|(k,v)| [k.to_sym,v]}] end
[ "def", "symbolize_keys", "(", "hash", ")", "Hash", "[", "hash", ".", "map", "{", "|", "(", "k", ",", "v", ")", "|", "[", "k", ".", "to_sym", ",", "v", "]", "}", "]", "end" ]
Accepts a hash and returns a new hash with symbolized keys
[ "Accepts", "a", "hash", "and", "returns", "a", "new", "hash", "with", "symbolized", "keys" ]
319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee
https://github.com/mdsol/representors/blob/319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee/lib/representor_support/utilities.rb#L5-L7
train
mdsol/representors
lib/representors/serialization/hale_deserializer.rb
Representors.HaleDeserializer.deserialize_embedded
def deserialize_embedded(builder, media) make_embedded_resource = ->(x) { self.class.new(x).to_representor_hash.to_h } (media[EMBEDDED_KEY] || {}).each do |name, value| resource_hash = map_or_apply(make_embedded_resource, value) builder = builder.add_embedded(name, resource_hash) end builder end
ruby
def deserialize_embedded(builder, media) make_embedded_resource = ->(x) { self.class.new(x).to_representor_hash.to_h } (media[EMBEDDED_KEY] || {}).each do |name, value| resource_hash = map_or_apply(make_embedded_resource, value) builder = builder.add_embedded(name, resource_hash) end builder end
[ "def", "deserialize_embedded", "(", "builder", ",", "media", ")", "make_embedded_resource", "=", "->", "(", "x", ")", "{", "self", ".", "class", ".", "new", "(", "x", ")", ".", "to_representor_hash", ".", "to_h", "}", "(", "media", "[", "EMBEDDED_KEY", "]", "||", "{", "}", ")", ".", "each", "do", "|", "name", ",", "value", "|", "resource_hash", "=", "map_or_apply", "(", "make_embedded_resource", ",", "value", ")", "builder", "=", "builder", ".", "add_embedded", "(", "name", ",", "resource_hash", ")", "end", "builder", "end" ]
embedded resources are under '_embedded' in the original document, similarly to links they can contain an array or a single embedded resource. An embedded resource is a full document so we create a new HaleDeserializer for each.
[ "embedded", "resources", "are", "under", "_embedded", "in", "the", "original", "document", "similarly", "to", "links", "they", "can", "contain", "an", "array", "or", "a", "single", "embedded", "resource", ".", "An", "embedded", "resource", "is", "a", "full", "document", "so", "we", "create", "a", "new", "HaleDeserializer", "for", "each", "." ]
319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee
https://github.com/mdsol/representors/blob/319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee/lib/representors/serialization/hale_deserializer.rb#L81-L88
train
mdsol/representors
lib/representors/representor_builder.rb
Representors.RepresentorBuilder.add_attribute
def add_attribute(name, value, options={}) new_representor_hash = RepresentorHash.new(deep_dup(@representor_hash.to_h)) new_representor_hash.attributes[name] = options.merge({value: value}) RepresentorBuilder.new(new_representor_hash) end
ruby
def add_attribute(name, value, options={}) new_representor_hash = RepresentorHash.new(deep_dup(@representor_hash.to_h)) new_representor_hash.attributes[name] = options.merge({value: value}) RepresentorBuilder.new(new_representor_hash) end
[ "def", "add_attribute", "(", "name", ",", "value", ",", "options", "=", "{", "}", ")", "new_representor_hash", "=", "RepresentorHash", ".", "new", "(", "deep_dup", "(", "@representor_hash", ".", "to_h", ")", ")", "new_representor_hash", ".", "attributes", "[", "name", "]", "=", "options", ".", "merge", "(", "{", "value", ":", "value", "}", ")", "RepresentorBuilder", ".", "new", "(", "new_representor_hash", ")", "end" ]
Adds an attribute to the Representor. We are creating a hash where the keys are the names of the attributes
[ "Adds", "an", "attribute", "to", "the", "Representor", ".", "We", "are", "creating", "a", "hash", "where", "the", "keys", "are", "the", "names", "of", "the", "attributes" ]
319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee
https://github.com/mdsol/representors/blob/319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee/lib/representors/representor_builder.rb#L27-L31
train
mdsol/representors
lib/representors/representor_builder.rb
Representors.RepresentorBuilder.add_transition
def add_transition(rel, href, options={}) new_representor_hash = RepresentorHash.new(deep_dup(@representor_hash.to_h)) options = symbolize_keys(options) options.delete(:method) if options[:method] == Transition::DEFAULT_METHOD link_values = options.merge({href: href, rel: rel}) if options[DATA_KEY] link_values[Transition::DESCRIPTORS_KEY] = link_values.delete(DATA_KEY) end new_representor_hash.transitions.push(link_values) RepresentorBuilder.new(new_representor_hash) end
ruby
def add_transition(rel, href, options={}) new_representor_hash = RepresentorHash.new(deep_dup(@representor_hash.to_h)) options = symbolize_keys(options) options.delete(:method) if options[:method] == Transition::DEFAULT_METHOD link_values = options.merge({href: href, rel: rel}) if options[DATA_KEY] link_values[Transition::DESCRIPTORS_KEY] = link_values.delete(DATA_KEY) end new_representor_hash.transitions.push(link_values) RepresentorBuilder.new(new_representor_hash) end
[ "def", "add_transition", "(", "rel", ",", "href", ",", "options", "=", "{", "}", ")", "new_representor_hash", "=", "RepresentorHash", ".", "new", "(", "deep_dup", "(", "@representor_hash", ".", "to_h", ")", ")", "options", "=", "symbolize_keys", "(", "options", ")", "options", ".", "delete", "(", ":method", ")", "if", "options", "[", ":method", "]", "==", "Transition", "::", "DEFAULT_METHOD", "link_values", "=", "options", ".", "merge", "(", "{", "href", ":", "href", ",", "rel", ":", "rel", "}", ")", "if", "options", "[", "DATA_KEY", "]", "link_values", "[", "Transition", "::", "DESCRIPTORS_KEY", "]", "=", "link_values", ".", "delete", "(", "DATA_KEY", ")", "end", "new_representor_hash", ".", "transitions", ".", "push", "(", "link_values", ")", "RepresentorBuilder", ".", "new", "(", "new_representor_hash", ")", "end" ]
Adds a transition to the Representor, each transition is a hash of values The transition collection is an Array
[ "Adds", "a", "transition", "to", "the", "Representor", "each", "transition", "is", "a", "hash", "of", "values", "The", "transition", "collection", "is", "an", "Array" ]
319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee
https://github.com/mdsol/representors/blob/319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee/lib/representors/representor_builder.rb#L35-L47
train
mdsol/representors
lib/representors/representor_builder.rb
Representors.RepresentorBuilder.add_transition_array
def add_transition_array(rel, array_of_hashes) array_of_hashes.reduce(RepresentorBuilder.new(@representor_hash)) do |memo, transition| transition = symbolize_keys(transition) href = transition.delete(:href) memo = memo.add_transition(rel, href, transition) end end
ruby
def add_transition_array(rel, array_of_hashes) array_of_hashes.reduce(RepresentorBuilder.new(@representor_hash)) do |memo, transition| transition = symbolize_keys(transition) href = transition.delete(:href) memo = memo.add_transition(rel, href, transition) end end
[ "def", "add_transition_array", "(", "rel", ",", "array_of_hashes", ")", "array_of_hashes", ".", "reduce", "(", "RepresentorBuilder", ".", "new", "(", "@representor_hash", ")", ")", "do", "|", "memo", ",", "transition", "|", "transition", "=", "symbolize_keys", "(", "transition", ")", "href", "=", "transition", ".", "delete", "(", ":href", ")", "memo", "=", "memo", ".", "add_transition", "(", "rel", ",", "href", ",", "transition", ")", "end", "end" ]
Adds directly an array to our array of transitions
[ "Adds", "directly", "an", "array", "to", "our", "array", "of", "transitions" ]
319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee
https://github.com/mdsol/representors/blob/319e5c1a42c93ef65a252ddd1e1a21dcc962a0ee/lib/representors/representor_builder.rb#L50-L56
train
rsim/oracle-enhanced
lib/active_record/connection_adapters/oracle_enhanced/procedures.rb
ActiveRecord.OracleEnhancedProcedures._create_record
def _create_record # check if class has custom create method if self.class.custom_create_method # run before/after callbacks defined in model run_callbacks(:create) do # timestamp if self.record_timestamps current_time = current_time_from_proper_timezone all_timestamp_attributes_in_model.each do |column| if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil? write_attribute(column.to_s, current_time) end end end # run create_using_custom_method end else super end end
ruby
def _create_record # check if class has custom create method if self.class.custom_create_method # run before/after callbacks defined in model run_callbacks(:create) do # timestamp if self.record_timestamps current_time = current_time_from_proper_timezone all_timestamp_attributes_in_model.each do |column| if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil? write_attribute(column.to_s, current_time) end end end # run create_using_custom_method end else super end end
[ "def", "_create_record", "# check if class has custom create method", "if", "self", ".", "class", ".", "custom_create_method", "# run before/after callbacks defined in model", "run_callbacks", "(", ":create", ")", "do", "# timestamp", "if", "self", ".", "record_timestamps", "current_time", "=", "current_time_from_proper_timezone", "all_timestamp_attributes_in_model", ".", "each", "do", "|", "column", "|", "if", "respond_to?", "(", "column", ")", "&&", "respond_to?", "(", "\"#{column}=\"", ")", "&&", "self", ".", "send", "(", "column", ")", ".", "nil?", "write_attribute", "(", "column", ".", "to_s", ",", "current_time", ")", "end", "end", "end", "# run", "create_using_custom_method", "end", "else", "super", "end", "end" ]
Creates a record with custom create method and returns its id.
[ "Creates", "a", "record", "with", "custom", "create", "method", "and", "returns", "its", "id", "." ]
03d4c557ceaf613ecce8657c47ebd9e936b31b7d
https://github.com/rsim/oracle-enhanced/blob/03d4c557ceaf613ecce8657c47ebd9e936b31b7d/lib/active_record/connection_adapters/oracle_enhanced/procedures.rb#L103-L124
train
rsim/oracle-enhanced
lib/active_record/connection_adapters/oracle_enhanced/procedures.rb
ActiveRecord.OracleEnhancedProcedures._update_record
def _update_record(attribute_names = @attributes.keys) # check if class has custom update method if self.class.custom_update_method # run before/after callbacks defined in model run_callbacks(:update) do # timestamp if should_record_timestamps? current_time = current_time_from_proper_timezone timestamp_attributes_for_update_in_model.each do |column| column = column.to_s next if will_save_change_to_attribute?(column) write_attribute(column, current_time) end end # update just dirty attributes if partial_writes? # Serialized attributes should always be written in case they've been # changed in place. update_using_custom_method(changed | (attributes.keys & self.class.columns.select { |column| column.is_a?(Type::Serialized) })) else update_using_custom_method(attributes.keys) end end else super end end
ruby
def _update_record(attribute_names = @attributes.keys) # check if class has custom update method if self.class.custom_update_method # run before/after callbacks defined in model run_callbacks(:update) do # timestamp if should_record_timestamps? current_time = current_time_from_proper_timezone timestamp_attributes_for_update_in_model.each do |column| column = column.to_s next if will_save_change_to_attribute?(column) write_attribute(column, current_time) end end # update just dirty attributes if partial_writes? # Serialized attributes should always be written in case they've been # changed in place. update_using_custom_method(changed | (attributes.keys & self.class.columns.select { |column| column.is_a?(Type::Serialized) })) else update_using_custom_method(attributes.keys) end end else super end end
[ "def", "_update_record", "(", "attribute_names", "=", "@attributes", ".", "keys", ")", "# check if class has custom update method", "if", "self", ".", "class", ".", "custom_update_method", "# run before/after callbacks defined in model", "run_callbacks", "(", ":update", ")", "do", "# timestamp", "if", "should_record_timestamps?", "current_time", "=", "current_time_from_proper_timezone", "timestamp_attributes_for_update_in_model", ".", "each", "do", "|", "column", "|", "column", "=", "column", ".", "to_s", "next", "if", "will_save_change_to_attribute?", "(", "column", ")", "write_attribute", "(", "column", ",", "current_time", ")", "end", "end", "# update just dirty attributes", "if", "partial_writes?", "# Serialized attributes should always be written in case they've been", "# changed in place.", "update_using_custom_method", "(", "changed", "|", "(", "attributes", ".", "keys", "&", "self", ".", "class", ".", "columns", ".", "select", "{", "|", "column", "|", "column", ".", "is_a?", "(", "Type", "::", "Serialized", ")", "}", ")", ")", "else", "update_using_custom_method", "(", "attributes", ".", "keys", ")", "end", "end", "else", "super", "end", "end" ]
Updates the associated record with custom update method Returns the number of affected rows.
[ "Updates", "the", "associated", "record", "with", "custom", "update", "method", "Returns", "the", "number", "of", "affected", "rows", "." ]
03d4c557ceaf613ecce8657c47ebd9e936b31b7d
https://github.com/rsim/oracle-enhanced/blob/03d4c557ceaf613ecce8657c47ebd9e936b31b7d/lib/active_record/connection_adapters/oracle_enhanced/procedures.rb#L138-L165
train
recurly/recurly-client-ruby
lib/recurly/coupon.rb
Recurly.Coupon.redeem
def redeem account_or_code, currency = nil, extra_opts={} return false unless link? :redeem account_code = if account_or_code.is_a? Account account_or_code.account_code else account_or_code end redemption_options = { :account_code => account_code, :currency => currency || Recurly.default_currency }.merge(extra_opts) redemption = Redemption.new(redemption_options) Redemption.from_response follow_link(:redeem, :body => redemption.to_xml ) rescue API::UnprocessableEntity => e redemption.apply_errors e redemption end
ruby
def redeem account_or_code, currency = nil, extra_opts={} return false unless link? :redeem account_code = if account_or_code.is_a? Account account_or_code.account_code else account_or_code end redemption_options = { :account_code => account_code, :currency => currency || Recurly.default_currency }.merge(extra_opts) redemption = Redemption.new(redemption_options) Redemption.from_response follow_link(:redeem, :body => redemption.to_xml ) rescue API::UnprocessableEntity => e redemption.apply_errors e redemption end
[ "def", "redeem", "account_or_code", ",", "currency", "=", "nil", ",", "extra_opts", "=", "{", "}", "return", "false", "unless", "link?", ":redeem", "account_code", "=", "if", "account_or_code", ".", "is_a?", "Account", "account_or_code", ".", "account_code", "else", "account_or_code", "end", "redemption_options", "=", "{", ":account_code", "=>", "account_code", ",", ":currency", "=>", "currency", "||", "Recurly", ".", "default_currency", "}", ".", "merge", "(", "extra_opts", ")", "redemption", "=", "Redemption", ".", "new", "(", "redemption_options", ")", "Redemption", ".", "from_response", "follow_link", "(", ":redeem", ",", ":body", "=>", "redemption", ".", "to_xml", ")", "rescue", "API", "::", "UnprocessableEntity", "=>", "e", "redemption", ".", "apply_errors", "e", "redemption", "end" ]
Redeem a coupon with a given account or account code. @return [true] @param account_or_code [Account, String] @param currency [String] Three-letter currency code @param extra_opts [Hash] extra options that go into the {Redemption} @example coupon = Coupon.find(coupon_code) coupon.redeem(account_code, 'USD', subscription_uuid: 'ab3b1dbabc3195') coupon = Coupon.find(coupon_code) account = Account.find(account_code) coupon.redeem(account)
[ "Redeem", "a", "coupon", "with", "a", "given", "account", "or", "account", "code", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/coupon.rb#L65-L87
train
recurly/recurly-client-ruby
lib/recurly/coupon.rb
Recurly.Coupon.generate
def generate(amount) builder = XML.new("<coupon/>") builder.add_element 'number_of_unique_codes', amount resp = follow_link(:generate, :body => builder.to_s ) Pager.new(Recurly::Coupon, uri: resp['location'], parent: self, etag: resp['ETag']) end
ruby
def generate(amount) builder = XML.new("<coupon/>") builder.add_element 'number_of_unique_codes', amount resp = follow_link(:generate, :body => builder.to_s ) Pager.new(Recurly::Coupon, uri: resp['location'], parent: self, etag: resp['ETag']) end
[ "def", "generate", "(", "amount", ")", "builder", "=", "XML", ".", "new", "(", "\"<coupon/>\"", ")", "builder", ".", "add_element", "'number_of_unique_codes'", ",", "amount", "resp", "=", "follow_link", "(", ":generate", ",", ":body", "=>", "builder", ".", "to_s", ")", "Pager", ".", "new", "(", "Recurly", "::", "Coupon", ",", "uri", ":", "resp", "[", "'location'", "]", ",", "parent", ":", "self", ",", "etag", ":", "resp", "[", "'ETag'", "]", ")", "end" ]
Generate unique coupon codes on the server. This is based on the unique_template_code. @param amount [Integer] @return [Pager<Coupon>] A pager that yields the coupon-code type Coupons @example unique_codes = coupon.generate(10) unique_codes.each do |c| puts c.coupon_code end
[ "Generate", "unique", "coupon", "codes", "on", "the", "server", ".", "This", "is", "based", "on", "the", "unique_template_code", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/coupon.rb#L98-L107
train
recurly/recurly-client-ruby
lib/recurly/coupon.rb
Recurly.Coupon.redeem!
def redeem!(account_code, currency = nil) redemption = redeem(account_code, currency) raise Invalid.new(self) unless redemption && redemption.persisted? redemption end
ruby
def redeem!(account_code, currency = nil) redemption = redeem(account_code, currency) raise Invalid.new(self) unless redemption && redemption.persisted? redemption end
[ "def", "redeem!", "(", "account_code", ",", "currency", "=", "nil", ")", "redemption", "=", "redeem", "(", "account_code", ",", "currency", ")", "raise", "Invalid", ".", "new", "(", "self", ")", "unless", "redemption", "&&", "redemption", ".", "persisted?", "redemption", "end" ]
Redeem a coupon on the given account code @param account_code [String] Acccount's account code @param currency [String] Three-letter currency code @raise [Invalid] If the coupon cannot be redeemed @return [Redemption] The Coupon Redemption
[ "Redeem", "a", "coupon", "on", "the", "given", "account", "code" ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/coupon.rb#L115-L119
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.read_attribute
def read_attribute(key) key = key.to_s if attributes.key? key value = attributes[key] elsif links.key?(key) && self.class.reflect_on_association(key) value = attributes[key] = follow_link key end value end
ruby
def read_attribute(key) key = key.to_s if attributes.key? key value = attributes[key] elsif links.key?(key) && self.class.reflect_on_association(key) value = attributes[key] = follow_link key end value end
[ "def", "read_attribute", "(", "key", ")", "key", "=", "key", ".", "to_s", "if", "attributes", ".", "key?", "key", "value", "=", "attributes", "[", "key", "]", "elsif", "links", ".", "key?", "(", "key", ")", "&&", "self", ".", "class", ".", "reflect_on_association", "(", "key", ")", "value", "=", "attributes", "[", "key", "]", "=", "follow_link", "key", "end", "value", "end" ]
The value of a specified attribute, lazily fetching any defined association. @param key [Symbol, String] The name of the attribute to be fetched. @example account.read_attribute :first_name # => "Ted" account[:last_name] # => "Beneke" @see #write_attribute
[ "The", "value", "of", "a", "specified", "attribute", "lazily", "fetching", "any", "defined", "association", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L722-L730
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.write_attribute
def write_attribute(key, value) if changed_attributes.key?(key = key.to_s) changed_attributes.delete key if changed_attributes[key] == value elsif self[key] != value changed_attributes[key] = self[key] end association = self.class.find_association(key) if association value = fetch_associated(key, value) # FIXME: More explicit; less magic. elsif value && key.end_with?('_in_cents') && !respond_to?(:currency) value = Money.new(value, self, key) unless value.is_a?(Money) end attributes[key] = value end
ruby
def write_attribute(key, value) if changed_attributes.key?(key = key.to_s) changed_attributes.delete key if changed_attributes[key] == value elsif self[key] != value changed_attributes[key] = self[key] end association = self.class.find_association(key) if association value = fetch_associated(key, value) # FIXME: More explicit; less magic. elsif value && key.end_with?('_in_cents') && !respond_to?(:currency) value = Money.new(value, self, key) unless value.is_a?(Money) end attributes[key] = value end
[ "def", "write_attribute", "(", "key", ",", "value", ")", "if", "changed_attributes", ".", "key?", "(", "key", "=", "key", ".", "to_s", ")", "changed_attributes", ".", "delete", "key", "if", "changed_attributes", "[", "key", "]", "==", "value", "elsif", "self", "[", "key", "]", "!=", "value", "changed_attributes", "[", "key", "]", "=", "self", "[", "key", "]", "end", "association", "=", "self", ".", "class", ".", "find_association", "(", "key", ")", "if", "association", "value", "=", "fetch_associated", "(", "key", ",", "value", ")", "# FIXME: More explicit; less magic.", "elsif", "value", "&&", "key", ".", "end_with?", "(", "'_in_cents'", ")", "&&", "!", "respond_to?", "(", ":currency", ")", "value", "=", "Money", ".", "new", "(", "value", ",", "self", ",", "key", ")", "unless", "value", ".", "is_a?", "(", "Money", ")", "end", "attributes", "[", "key", "]", "=", "value", "end" ]
Sets the value of a specified attribute. @param key [Symbol, String] The name of the attribute to be set. @param value [Object] The value the attribute will be set to. @example account.write_attribute :first_name, 'Gus' account[:company_name] = 'Los Pollos Hermanos' @see #read_attribute
[ "Sets", "the", "value", "of", "a", "specified", "attribute", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L741-L757
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.attributes=
def attributes=(attributes = {}) attributes.each_pair { |k, v| respond_to?(name = "#{k}=") and send(name, v) or self[k] = v } end
ruby
def attributes=(attributes = {}) attributes.each_pair { |k, v| respond_to?(name = "#{k}=") and send(name, v) or self[k] = v } end
[ "def", "attributes", "=", "(", "attributes", "=", "{", "}", ")", "attributes", ".", "each_pair", "{", "|", "k", ",", "v", "|", "respond_to?", "(", "name", "=", "\"#{k}=\"", ")", "and", "send", "(", "name", ",", "v", ")", "or", "self", "[", "k", "]", "=", "v", "}", "end" ]
Apply a given hash of attributes to a record. @return [Hash] @param attributes [Hash] A hash of attributes.
[ "Apply", "a", "given", "hash", "of", "attributes", "to", "a", "record", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L764-L768
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.follow_link
def follow_link(key, options = {}) if link = links[key = key.to_s] response = API.send link[:method], link[:href], options[:body], options if resource_class = link[:resource_class] response = resource_class.from_response response response.attributes[self.class.member_name] = self end response end rescue Recurly::API::NotFound raise unless resource_class end
ruby
def follow_link(key, options = {}) if link = links[key = key.to_s] response = API.send link[:method], link[:href], options[:body], options if resource_class = link[:resource_class] response = resource_class.from_response response response.attributes[self.class.member_name] = self end response end rescue Recurly::API::NotFound raise unless resource_class end
[ "def", "follow_link", "(", "key", ",", "options", "=", "{", "}", ")", "if", "link", "=", "links", "[", "key", "=", "key", ".", "to_s", "]", "response", "=", "API", ".", "send", "link", "[", ":method", "]", ",", "link", "[", ":href", "]", ",", "options", "[", ":body", "]", ",", "options", "if", "resource_class", "=", "link", "[", ":resource_class", "]", "response", "=", "resource_class", ".", "from_response", "response", "response", ".", "attributes", "[", "self", ".", "class", ".", "member_name", "]", "=", "self", "end", "response", "end", "rescue", "Recurly", "::", "API", "::", "NotFound", "raise", "unless", "resource_class", "end" ]
Fetch the value of a link by following the associated href. @param key [Symbol, String] The name of the link to be followed. @param options [Hash] A hash of API options. @example account.read_link :billing_info # => <Recurly::BillingInfo>
[ "Fetch", "the", "value", "of", "a", "link", "by", "following", "the", "associated", "href", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L794-L805
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.to_xml
def to_xml(options = {}) builder = options[:builder] || XML.new("<#{self.class.member_name}/>") xml_keys.each { |key| value = respond_to?(key) ? send(key) : self[key] node = builder.add_element key # Duck-typing here is problematic because of ActiveSupport's #to_xml. case value when Resource, Subscription::AddOns value.to_xml options.merge(:builder => node) when Array value.each do |e| if e.is_a? Recurly::Resource # create a node to hold this resource e_node = node.add_element Helper.singularize(key) # serialize the resource into this node e.to_xml(options.merge(builder: e_node)) else # it's just a primitive value node.add_element(Helper.singularize(key), e) end end when Hash, Recurly::Money value.each_pair { |k, v| node.add_element k.to_s, v } else node.text = value end } builder.to_s end
ruby
def to_xml(options = {}) builder = options[:builder] || XML.new("<#{self.class.member_name}/>") xml_keys.each { |key| value = respond_to?(key) ? send(key) : self[key] node = builder.add_element key # Duck-typing here is problematic because of ActiveSupport's #to_xml. case value when Resource, Subscription::AddOns value.to_xml options.merge(:builder => node) when Array value.each do |e| if e.is_a? Recurly::Resource # create a node to hold this resource e_node = node.add_element Helper.singularize(key) # serialize the resource into this node e.to_xml(options.merge(builder: e_node)) else # it's just a primitive value node.add_element(Helper.singularize(key), e) end end when Hash, Recurly::Money value.each_pair { |k, v| node.add_element k.to_s, v } else node.text = value end } builder.to_s end
[ "def", "to_xml", "(", "options", "=", "{", "}", ")", "builder", "=", "options", "[", ":builder", "]", "||", "XML", ".", "new", "(", "\"<#{self.class.member_name}/>\"", ")", "xml_keys", ".", "each", "{", "|", "key", "|", "value", "=", "respond_to?", "(", "key", ")", "?", "send", "(", "key", ")", ":", "self", "[", "key", "]", "node", "=", "builder", ".", "add_element", "key", "# Duck-typing here is problematic because of ActiveSupport's #to_xml.", "case", "value", "when", "Resource", ",", "Subscription", "::", "AddOns", "value", ".", "to_xml", "options", ".", "merge", "(", ":builder", "=>", "node", ")", "when", "Array", "value", ".", "each", "do", "|", "e", "|", "if", "e", ".", "is_a?", "Recurly", "::", "Resource", "# create a node to hold this resource", "e_node", "=", "node", ".", "add_element", "Helper", ".", "singularize", "(", "key", ")", "# serialize the resource into this node", "e", ".", "to_xml", "(", "options", ".", "merge", "(", "builder", ":", "e_node", ")", ")", "else", "# it's just a primitive value", "node", ".", "add_element", "(", "Helper", ".", "singularize", "(", "key", ")", ",", "e", ")", "end", "end", "when", "Hash", ",", "Recurly", "::", "Money", "value", ".", "each_pair", "{", "|", "k", ",", "v", "|", "node", ".", "add_element", "k", ".", "to_s", ",", "v", "}", "else", "node", ".", "text", "=", "value", "end", "}", "builder", ".", "to_s", "end" ]
Serializes the record to XML. @return [String] An XML string. @param options [Hash] A hash of XML options. @example Recurly::Account.new(:account_code => 'code').to_xml # => "<account><account_code>code</account_code></account>"
[ "Serializes", "the", "record", "to", "XML", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L814-L843
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.save
def save if new_record? || changed? clear_errors @response = API.send( persisted? ? :put : :post, path, to_xml ) reload response persist! true end true rescue API::UnprocessableEntity => e apply_errors e Transaction::Error.validate! e, (self if is_a?(Transaction)) false end
ruby
def save if new_record? || changed? clear_errors @response = API.send( persisted? ? :put : :post, path, to_xml ) reload response persist! true end true rescue API::UnprocessableEntity => e apply_errors e Transaction::Error.validate! e, (self if is_a?(Transaction)) false end
[ "def", "save", "if", "new_record?", "||", "changed?", "clear_errors", "@response", "=", "API", ".", "send", "(", "persisted?", "?", ":put", ":", ":post", ",", "path", ",", "to_xml", ")", "reload", "response", "persist!", "true", "end", "true", "rescue", "API", "::", "UnprocessableEntity", "=>", "e", "apply_errors", "e", "Transaction", "::", "Error", ".", "validate!", "e", ",", "(", "self", "if", "is_a?", "(", "Transaction", ")", ")", "false", "end" ]
Attempts to save the record, returning the success of the request. @return [true, false] @raise [Transaction::Error] A monetary transaction failed. @example account = Recurly::Account.new account.save # => false account.account_code = 'account_code' account.save # => true @see #save!
[ "Attempts", "to", "save", "the", "record", "returning", "the", "success", "of", "the", "request", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L855-L869
train
recurly/recurly-client-ruby
lib/recurly/resource.rb
Recurly.Resource.destroy
def destroy return false unless persisted? @response = API.delete uri @destroyed = true rescue API::NotFound => e raise NotFound, e.description end
ruby
def destroy return false unless persisted? @response = API.delete uri @destroyed = true rescue API::NotFound => e raise NotFound, e.description end
[ "def", "destroy", "return", "false", "unless", "persisted?", "@response", "=", "API", ".", "delete", "uri", "@destroyed", "=", "true", "rescue", "API", "::", "NotFound", "=>", "e", "raise", "NotFound", ",", "e", ".", "description", "end" ]
Attempts to destroy the record. @return [true, false] +true+ if successful, +false+ if unable to destroy (if the record does not persist on Recurly). @raise [NotFound] The record cannot be found. @example account = Recurly::Account.find account_code race_condition = Recurly::Account.find account_code account.destroy # => true account.destroy # => false (already destroyed) race_condition.destroy # raises Recurly::Resource::NotFound
[ "Attempts", "to", "destroy", "the", "record", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/resource.rb#L980-L986
train
recurly/recurly-client-ruby
lib/recurly/account.rb
Recurly.Account.invoice!
def invoice!(attrs={}) InvoiceCollection.from_response API.post(invoices.uri, attrs.empty? ? nil : Invoice.to_xml(attrs)) rescue Recurly::API::UnprocessableEntity => e raise Invalid, e.message end
ruby
def invoice!(attrs={}) InvoiceCollection.from_response API.post(invoices.uri, attrs.empty? ? nil : Invoice.to_xml(attrs)) rescue Recurly::API::UnprocessableEntity => e raise Invalid, e.message end
[ "def", "invoice!", "(", "attrs", "=", "{", "}", ")", "InvoiceCollection", ".", "from_response", "API", ".", "post", "(", "invoices", ".", "uri", ",", "attrs", ".", "empty?", "?", "nil", ":", "Invoice", ".", "to_xml", "(", "attrs", ")", ")", "rescue", "Recurly", "::", "API", "::", "UnprocessableEntity", "=>", "e", "raise", "Invalid", ",", "e", ".", "message", "end" ]
Creates an invoice from the pending charges on the account. Raises an error if it fails. @return [InvoiceCollection] A newly-created invoice. @raise [Invalid] Raised if the account cannot be invoiced.
[ "Creates", "an", "invoice", "from", "the", "pending", "charges", "on", "the", "account", ".", "Raises", "an", "error", "if", "it", "fails", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/account.rb#L109-L113
train
recurly/recurly-client-ruby
lib/recurly/account.rb
Recurly.Account.build_invoice
def build_invoice InvoiceCollection.from_response API.post("#{invoices.uri}/preview") rescue Recurly::API::UnprocessableEntity => e raise Invalid, e.message end
ruby
def build_invoice InvoiceCollection.from_response API.post("#{invoices.uri}/preview") rescue Recurly::API::UnprocessableEntity => e raise Invalid, e.message end
[ "def", "build_invoice", "InvoiceCollection", ".", "from_response", "API", ".", "post", "(", "\"#{invoices.uri}/preview\"", ")", "rescue", "Recurly", "::", "API", "::", "UnprocessableEntity", "=>", "e", "raise", "Invalid", ",", "e", ".", "message", "end" ]
Builds an invoice from the pending charges on the account but does not persist the invoice. Raises an error if it fails. @return [InvoiceCollection] The newly-built invoice that has not been persisted. @raise [Invalid] Raised if the account cannot be invoiced.
[ "Builds", "an", "invoice", "from", "the", "pending", "charges", "on", "the", "account", "but", "does", "not", "persist", "the", "invoice", ".", "Raises", "an", "error", "if", "it", "fails", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/account.rb#L120-L124
train
recurly/recurly-client-ruby
lib/recurly/account.rb
Recurly.Account.verify_cvv!
def verify_cvv!(verification_value) bi = BillingInfo.new(verification_value: verification_value) bi.uri = "#{path}/billing_info/verify_cvv" bi.save! bi end
ruby
def verify_cvv!(verification_value) bi = BillingInfo.new(verification_value: verification_value) bi.uri = "#{path}/billing_info/verify_cvv" bi.save! bi end
[ "def", "verify_cvv!", "(", "verification_value", ")", "bi", "=", "BillingInfo", ".", "new", "(", "verification_value", ":", "verification_value", ")", "bi", ".", "uri", "=", "\"#{path}/billing_info/verify_cvv\"", "bi", ".", "save!", "bi", "end" ]
Verify a cvv code for the account's billing info. @example acct = Recurly::Account.find('benjamin-du-monde') begin # If successful, returned billing_info will contain # updated billing info details. billing_info = acct.verify_cvv!("504") rescue Recurly::API::BadRequest => e e.message # => "This credit card has too many cvv check attempts." rescue Recurly::Transaction::Error => e # this will be the errors coming back from gateway e.transaction_error_code # => "fraud_security_code" e.gateway_error_code # => "fraud" rescue Recurly::Resource::Invalid => e e.message # => "verification_value must be three digits" end @param [String] verification_value The CVV code to check @return [BillingInfo] The updated billing info @raise [Recurly::Transaction::Error] A Transaction Error will be raised if the gateway declines the cvv code. @raise [API::BadRequest] A BadRequest error will be raised if you attempt to check too many times and are locked out. @raise [Resource::Invalid] An Invalid Error will be raised if you send an invalid request (such as a value that is not a propert verification number).
[ "Verify", "a", "cvv", "code", "for", "the", "account", "s", "billing", "info", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/account.rb#L163-L168
train
recurly/recurly-client-ruby
lib/recurly/invoice.rb
Recurly.Invoice.enter_offline_payment
def enter_offline_payment(attrs={}) Transaction.from_response API.post("#{uri}/transactions", attrs.empty? ? nil : Transaction.to_xml(attrs)) rescue Recurly::API::UnprocessableEntity => e raise Invalid, e.message end
ruby
def enter_offline_payment(attrs={}) Transaction.from_response API.post("#{uri}/transactions", attrs.empty? ? nil : Transaction.to_xml(attrs)) rescue Recurly::API::UnprocessableEntity => e raise Invalid, e.message end
[ "def", "enter_offline_payment", "(", "attrs", "=", "{", "}", ")", "Transaction", ".", "from_response", "API", ".", "post", "(", "\"#{uri}/transactions\"", ",", "attrs", ".", "empty?", "?", "nil", ":", "Transaction", ".", "to_xml", "(", "attrs", ")", ")", "rescue", "Recurly", "::", "API", "::", "UnprocessableEntity", "=>", "e", "raise", "Invalid", ",", "e", ".", "message", "end" ]
Posts an offline payment on this invoice @return [Transaction] @raise [Error] If the transaction fails.
[ "Posts", "an", "offline", "payment", "on", "this", "invoice" ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/invoice.rb#L167-L171
train
recurly/recurly-client-ruby
lib/recurly/gift_card.rb
Recurly.GiftCard.preview
def preview clear_errors @response = API.send(:post, "#{path}/preview", to_xml) reload response rescue API::UnprocessableEntity => e apply_errors e end
ruby
def preview clear_errors @response = API.send(:post, "#{path}/preview", to_xml) reload response rescue API::UnprocessableEntity => e apply_errors e end
[ "def", "preview", "clear_errors", "@response", "=", "API", ".", "send", "(", ":post", ",", "\"#{path}/preview\"", ",", "to_xml", ")", "reload", "response", "rescue", "API", "::", "UnprocessableEntity", "=>", "e", "apply_errors", "e", "end" ]
Preview the GiftCard. Runs and validates the GiftCard but does not persist it. Errors are applied to the GiftCard if there are any errors.
[ "Preview", "the", "GiftCard", ".", "Runs", "and", "validates", "the", "GiftCard", "but", "does", "not", "persist", "it", ".", "Errors", "are", "applied", "to", "the", "GiftCard", "if", "there", "are", "any", "errors", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/gift_card.rb#L50-L56
train
recurly/recurly-client-ruby
lib/recurly/subscription.rb
Recurly.Subscription.postpone
def postpone next_renewal_date, bulk=false return false unless link? :postpone reload follow_link(:postpone, :params => { :next_renewal_date => next_renewal_date, :bulk => bulk } ) true end
ruby
def postpone next_renewal_date, bulk=false return false unless link? :postpone reload follow_link(:postpone, :params => { :next_renewal_date => next_renewal_date, :bulk => bulk } ) true end
[ "def", "postpone", "next_renewal_date", ",", "bulk", "=", "false", "return", "false", "unless", "link?", ":postpone", "reload", "follow_link", "(", ":postpone", ",", ":params", "=>", "{", ":next_renewal_date", "=>", "next_renewal_date", ",", ":bulk", "=>", "bulk", "}", ")", "true", "end" ]
Postpone a subscription's renewal date. @return [true, false] +true+ when successful, +false+ when unable to (e.g., the subscription is not active). @param next_renewal_date [Time] when the subscription should renew. @param bulk [boolean] set to true for bulk updates (bypassing 60 second wait).
[ "Postpone", "a", "subscription", "s", "renewal", "date", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/subscription.rb#L228-L234
train
recurly/recurly-client-ruby
lib/recurly/subscription.rb
Recurly.Subscription.update_notes
def update_notes(notes) return false unless link? :notes self.attributes = notes reload follow_link(:notes, body: to_xml) true end
ruby
def update_notes(notes) return false unless link? :notes self.attributes = notes reload follow_link(:notes, body: to_xml) true end
[ "def", "update_notes", "(", "notes", ")", "return", "false", "unless", "link?", ":notes", "self", ".", "attributes", "=", "notes", "reload", "follow_link", "(", ":notes", ",", "body", ":", "to_xml", ")", "true", "end" ]
Update the notes sections of the subscription. This endpoint also allows you to update the custom fields. @example subscription.custom_fields.first.value = nil subscription.update_notes(terms_and_conditions: 'New T&C') #=> # <subscription> # <custom_fields><custom_field><name>food</name><value nil="nil"/><custom_field></custom_fields> # <terms_and_conditions>New T&C</terms_and_conditions> # </subscription> # it's also okay to call without notes subscription.update_notes({}) @param notes [Hash] should be the notes parameters you wish to update @return [true, false] +true+ when successful, +false+ when unable to
[ "Update", "the", "notes", "sections", "of", "the", "subscription", ".", "This", "endpoint", "also", "allows", "you", "to", "update", "the", "custom", "fields", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/subscription.rb#L252-L257
train
recurly/recurly-client-ruby
lib/recurly/subscription.rb
Recurly.Subscription.pause
def pause(remaining_pause_cycles) builder = XML.new("<subscription/>") builder.add_element('remaining_pause_cycles', remaining_pause_cycles) reload API.put("#{uri}/pause", builder.to_s) true end
ruby
def pause(remaining_pause_cycles) builder = XML.new("<subscription/>") builder.add_element('remaining_pause_cycles', remaining_pause_cycles) reload API.put("#{uri}/pause", builder.to_s) true end
[ "def", "pause", "(", "remaining_pause_cycles", ")", "builder", "=", "XML", ".", "new", "(", "\"<subscription/>\"", ")", "builder", ".", "add_element", "(", "'remaining_pause_cycles'", ",", "remaining_pause_cycles", ")", "reload", "API", ".", "put", "(", "\"#{uri}/pause\"", ",", "builder", ".", "to_s", ")", "true", "end" ]
Pauses a subscription or cancels a scheduled pause. * For an active subscription without a pause scheduled already, this will schedule a pause period to begin at the next renewal date for the specified number of billing cycles (remaining_pause_cycles). * When a scheduled pause already exists, this will update the remaining pause cycles with the new value sent. When zero (0) remaining_pause_cycles is sent for a subscription with a scheduled pause, the pause will be canceled. * For a paused subscription, the remaining_pause_cycles will adjust the length of the current pause period. Sending zero (0) in the remaining_pause_cycles field will cause the subscription to be resumed at the next renewal date. @param remaining_pause_cycles [Integer] The number of billing cycles that the subscription will be paused. @return true
[ "Pauses", "a", "subscription", "or", "cancels", "a", "scheduled", "pause", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/subscription.rb#L273-L278
train
recurly/recurly-client-ruby
lib/recurly/xml.rb
Recurly.XML.add_element
def add_element name, value = nil value = value.respond_to?(:xmlschema) ? value.xmlschema : value.to_s XML.new super(name, value) end
ruby
def add_element name, value = nil value = value.respond_to?(:xmlschema) ? value.xmlschema : value.to_s XML.new super(name, value) end
[ "def", "add_element", "name", ",", "value", "=", "nil", "value", "=", "value", ".", "respond_to?", "(", ":xmlschema", ")", "?", "value", ".", "xmlschema", ":", "value", ".", "to_s", "XML", ".", "new", "super", "(", "name", ",", "value", ")", "end" ]
Adds an element to the root.
[ "Adds", "an", "element", "to", "the", "root", "." ]
3726114fdf584ba50982e0ee28fd219136043fbc
https://github.com/recurly/recurly-client-ruby/blob/3726114fdf584ba50982e0ee28fd219136043fbc/lib/recurly/xml.rb#L65-L68
train
rodjek/rspec-puppet
lib/rspec-puppet/coverage.rb
RSpec::Puppet.Coverage.add_from_catalog
def add_from_catalog(catalog, test_module) coverable_resources = catalog.to_a.reject { |resource| !test_module.nil? && filter_resource?(resource, test_module) } coverable_resources.each do |resource| add(resource) end end
ruby
def add_from_catalog(catalog, test_module) coverable_resources = catalog.to_a.reject { |resource| !test_module.nil? && filter_resource?(resource, test_module) } coverable_resources.each do |resource| add(resource) end end
[ "def", "add_from_catalog", "(", "catalog", ",", "test_module", ")", "coverable_resources", "=", "catalog", ".", "to_a", ".", "reject", "{", "|", "resource", "|", "!", "test_module", ".", "nil?", "&&", "filter_resource?", "(", "resource", ",", "test_module", ")", "}", "coverable_resources", ".", "each", "do", "|", "resource", "|", "add", "(", "resource", ")", "end", "end" ]
add all resources from catalog declared in module test_module
[ "add", "all", "resources", "from", "catalog", "declared", "in", "module", "test_module" ]
5cc25d0083a4abc352ab13bd48f225f668311a3e
https://github.com/rodjek/rspec-puppet/blob/5cc25d0083a4abc352ab13bd48f225f668311a3e/lib/rspec-puppet/coverage.rb#L102-L107
train
rodjek/rspec-puppet
lib/rspec-puppet/coverage.rb
RSpec::Puppet.Coverage.filter_resource?
def filter_resource?(resource, test_module) if @filters.include?(resource.to_s) return true end if resource.type == 'Class' module_name = resource.title.split('::').first.downcase if module_name != test_module return true end end if resource.file paths = module_paths(test_module) unless paths.any? { |path| resource.file.include?(path) } return true end end return false end
ruby
def filter_resource?(resource, test_module) if @filters.include?(resource.to_s) return true end if resource.type == 'Class' module_name = resource.title.split('::').first.downcase if module_name != test_module return true end end if resource.file paths = module_paths(test_module) unless paths.any? { |path| resource.file.include?(path) } return true end end return false end
[ "def", "filter_resource?", "(", "resource", ",", "test_module", ")", "if", "@filters", ".", "include?", "(", "resource", ".", "to_s", ")", "return", "true", "end", "if", "resource", ".", "type", "==", "'Class'", "module_name", "=", "resource", ".", "title", ".", "split", "(", "'::'", ")", ".", "first", ".", "downcase", "if", "module_name", "!=", "test_module", "return", "true", "end", "end", "if", "resource", ".", "file", "paths", "=", "module_paths", "(", "test_module", ")", "unless", "paths", ".", "any?", "{", "|", "path", "|", "resource", ".", "file", ".", "include?", "(", "path", ")", "}", "return", "true", "end", "end", "return", "false", "end" ]
Should this resource be excluded from coverage reports? The resource is not included in coverage reports if any of the conditions hold: * The resource has been explicitly filtered out. * Examples: autogenerated resources such as 'Stage[main]' * The resource is a class but does not belong to the module under test. * Examples: Class dependencies included from a fixture module * The resource was declared in a file outside of the test module or site.pp * Examples: Resources declared in a dependency of this module. @param resource [Puppet::Resource] The resource that may be filtered @param test_module [String] The name of the module under test @return [true, false]
[ "Should", "this", "resource", "be", "excluded", "from", "coverage", "reports?" ]
5cc25d0083a4abc352ab13bd48f225f668311a3e
https://github.com/rodjek/rspec-puppet/blob/5cc25d0083a4abc352ab13bd48f225f668311a3e/lib/rspec-puppet/coverage.rb#L217-L237
train
rodjek/rspec-puppet
lib/rspec-puppet/coverage.rb
RSpec::Puppet.Coverage.module_paths
def module_paths(test_module) adapter = RSpec.configuration.adapter paths = adapter.modulepath.map do |dir| File.join(dir, test_module, 'manifests') end paths << adapter.manifest if adapter.manifest paths end
ruby
def module_paths(test_module) adapter = RSpec.configuration.adapter paths = adapter.modulepath.map do |dir| File.join(dir, test_module, 'manifests') end paths << adapter.manifest if adapter.manifest paths end
[ "def", "module_paths", "(", "test_module", ")", "adapter", "=", "RSpec", ".", "configuration", ".", "adapter", "paths", "=", "adapter", ".", "modulepath", ".", "map", "do", "|", "dir", "|", "File", ".", "join", "(", "dir", ",", "test_module", ",", "'manifests'", ")", "end", "paths", "<<", "adapter", ".", "manifest", "if", "adapter", ".", "manifest", "paths", "end" ]
Find all paths that may contain testable resources for a module. @return [Array<String>]
[ "Find", "all", "paths", "that", "may", "contain", "testable", "resources", "for", "a", "module", "." ]
5cc25d0083a4abc352ab13bd48f225f668311a3e
https://github.com/rodjek/rspec-puppet/blob/5cc25d0083a4abc352ab13bd48f225f668311a3e/lib/rspec-puppet/coverage.rb#L242-L249
train
rodjek/rspec-puppet
lib/rspec-puppet/example/function_example_group.rb
RSpec::Puppet.FunctionExampleGroup.build_compiler
def build_compiler node_name = nodename(:function) fact_values = facts_hash(node_name) trusted_values = trusted_facts_hash(node_name) # Allow different Hiera configurations: HieraPuppet.instance_variable_set('@hiera', nil) if defined? HieraPuppet # if we specify a pre_condition, we should ensure that we compile that # code into a catalog that is accessible from the scope where the # function is called Puppet[:code] = pre_cond node_facts = Puppet::Node::Facts.new(node_name, fact_values.dup) node_options = { :parameters => fact_values, :facts => node_facts } stub_facts! fact_values node = build_node(node_name, node_options) if Puppet::Util::Package.versioncmp(Puppet.version, '4.3.0') >= 0 Puppet.push_context( { :trusted_information => Puppet::Context::TrustedInformation.new('remote', node_name, trusted_values) }, "Context for spec trusted hash" ) end compiler = Puppet::Parser::Compiler.new(node) compiler.compile if Puppet::Util::Package.versioncmp(Puppet.version, '4.0.0') >= 0 loaders = Puppet::Pops::Loaders.new(adapter.current_environment) Puppet.push_context( { :loaders => loaders, :global_scope => compiler.context_overrides[:global_scope] }, "set globals") end compiler end
ruby
def build_compiler node_name = nodename(:function) fact_values = facts_hash(node_name) trusted_values = trusted_facts_hash(node_name) # Allow different Hiera configurations: HieraPuppet.instance_variable_set('@hiera', nil) if defined? HieraPuppet # if we specify a pre_condition, we should ensure that we compile that # code into a catalog that is accessible from the scope where the # function is called Puppet[:code] = pre_cond node_facts = Puppet::Node::Facts.new(node_name, fact_values.dup) node_options = { :parameters => fact_values, :facts => node_facts } stub_facts! fact_values node = build_node(node_name, node_options) if Puppet::Util::Package.versioncmp(Puppet.version, '4.3.0') >= 0 Puppet.push_context( { :trusted_information => Puppet::Context::TrustedInformation.new('remote', node_name, trusted_values) }, "Context for spec trusted hash" ) end compiler = Puppet::Parser::Compiler.new(node) compiler.compile if Puppet::Util::Package.versioncmp(Puppet.version, '4.0.0') >= 0 loaders = Puppet::Pops::Loaders.new(adapter.current_environment) Puppet.push_context( { :loaders => loaders, :global_scope => compiler.context_overrides[:global_scope] }, "set globals") end compiler end
[ "def", "build_compiler", "node_name", "=", "nodename", "(", ":function", ")", "fact_values", "=", "facts_hash", "(", "node_name", ")", "trusted_values", "=", "trusted_facts_hash", "(", "node_name", ")", "# Allow different Hiera configurations:", "HieraPuppet", ".", "instance_variable_set", "(", "'@hiera'", ",", "nil", ")", "if", "defined?", "HieraPuppet", "# if we specify a pre_condition, we should ensure that we compile that", "# code into a catalog that is accessible from the scope where the", "# function is called", "Puppet", "[", ":code", "]", "=", "pre_cond", "node_facts", "=", "Puppet", "::", "Node", "::", "Facts", ".", "new", "(", "node_name", ",", "fact_values", ".", "dup", ")", "node_options", "=", "{", ":parameters", "=>", "fact_values", ",", ":facts", "=>", "node_facts", "}", "stub_facts!", "fact_values", "node", "=", "build_node", "(", "node_name", ",", "node_options", ")", "if", "Puppet", "::", "Util", "::", "Package", ".", "versioncmp", "(", "Puppet", ".", "version", ",", "'4.3.0'", ")", ">=", "0", "Puppet", ".", "push_context", "(", "{", ":trusted_information", "=>", "Puppet", "::", "Context", "::", "TrustedInformation", ".", "new", "(", "'remote'", ",", "node_name", ",", "trusted_values", ")", "}", ",", "\"Context for spec trusted hash\"", ")", "end", "compiler", "=", "Puppet", "::", "Parser", "::", "Compiler", ".", "new", "(", "node", ")", "compiler", ".", "compile", "if", "Puppet", "::", "Util", "::", "Package", ".", "versioncmp", "(", "Puppet", ".", "version", ",", "'4.0.0'", ")", ">=", "0", "loaders", "=", "Puppet", "::", "Pops", "::", "Loaders", ".", "new", "(", "adapter", ".", "current_environment", ")", "Puppet", ".", "push_context", "(", "{", ":loaders", "=>", "loaders", ",", ":global_scope", "=>", "compiler", ".", "context_overrides", "[", ":global_scope", "]", "}", ",", "\"set globals\"", ")", "end", "compiler", "end" ]
get a compiler with an attached compiled catalog
[ "get", "a", "compiler", "with", "an", "attached", "compiled", "catalog" ]
5cc25d0083a4abc352ab13bd48f225f668311a3e
https://github.com/rodjek/rspec-puppet/blob/5cc25d0083a4abc352ab13bd48f225f668311a3e/lib/rspec-puppet/example/function_example_group.rb#L132-L177
train
ManageIQ/manageiq-smartstate
lib/VolumeManager/LVM/thin/superblock.rb
Lvm2Thin.SuperBlock.device_to_data
def device_to_data(device_id, pos, len) dev_blk = device_block(pos) dev_off = device_block_offset(pos) data_map = data_mapping.map_for(device_id) total_len = 0 data_blks = [] num_data_blks = (len / data_block_size).to_i + 1 0.upto(num_data_blks - 1) do |i| current_blk = dev_blk + i blk_len = 0 if data_map.block?(current_blk) data_blk = data_map.data_block(current_blk) blk_start = data_blk * data_block_size if i.zero? blk_start += dev_off blk_len = data_block_size - dev_off - 1 elsif i == num_data_blks - 1 blk_len = len - total_len else blk_len = data_block_size end data_blks << [current_blk, data_blk, blk_start, blk_len] # Missing block may be caused by trying to read beyond end of # LVM device (too large pos or len): else remaining = (len - total_len) blk_len = remaining > data_block_size ? data_block_size : remaining data_blks << [current_blk, nil, nil, blk_len] end total_len += blk_len end data_blks end
ruby
def device_to_data(device_id, pos, len) dev_blk = device_block(pos) dev_off = device_block_offset(pos) data_map = data_mapping.map_for(device_id) total_len = 0 data_blks = [] num_data_blks = (len / data_block_size).to_i + 1 0.upto(num_data_blks - 1) do |i| current_blk = dev_blk + i blk_len = 0 if data_map.block?(current_blk) data_blk = data_map.data_block(current_blk) blk_start = data_blk * data_block_size if i.zero? blk_start += dev_off blk_len = data_block_size - dev_off - 1 elsif i == num_data_blks - 1 blk_len = len - total_len else blk_len = data_block_size end data_blks << [current_blk, data_blk, blk_start, blk_len] # Missing block may be caused by trying to read beyond end of # LVM device (too large pos or len): else remaining = (len - total_len) blk_len = remaining > data_block_size ? data_block_size : remaining data_blks << [current_blk, nil, nil, blk_len] end total_len += blk_len end data_blks end
[ "def", "device_to_data", "(", "device_id", ",", "pos", ",", "len", ")", "dev_blk", "=", "device_block", "(", "pos", ")", "dev_off", "=", "device_block_offset", "(", "pos", ")", "data_map", "=", "data_mapping", ".", "map_for", "(", "device_id", ")", "total_len", "=", "0", "data_blks", "=", "[", "]", "num_data_blks", "=", "(", "len", "/", "data_block_size", ")", ".", "to_i", "+", "1", "0", ".", "upto", "(", "num_data_blks", "-", "1", ")", "do", "|", "i", "|", "current_blk", "=", "dev_blk", "+", "i", "blk_len", "=", "0", "if", "data_map", ".", "block?", "(", "current_blk", ")", "data_blk", "=", "data_map", ".", "data_block", "(", "current_blk", ")", "blk_start", "=", "data_blk", "*", "data_block_size", "if", "i", ".", "zero?", "blk_start", "+=", "dev_off", "blk_len", "=", "data_block_size", "-", "dev_off", "-", "1", "elsif", "i", "==", "num_data_blks", "-", "1", "blk_len", "=", "len", "-", "total_len", "else", "blk_len", "=", "data_block_size", "end", "data_blks", "<<", "[", "current_blk", ",", "data_blk", ",", "blk_start", ",", "blk_len", "]", "# Missing block may be caused by trying to read beyond end of", "# LVM device (too large pos or len):", "else", "remaining", "=", "(", "len", "-", "total_len", ")", "blk_len", "=", "remaining", ">", "data_block_size", "?", "data_block_size", ":", "remaining", "data_blks", "<<", "[", "current_blk", ",", "nil", ",", "nil", ",", "blk_len", "]", "end", "total_len", "+=", "blk_len", "end", "data_blks", "end" ]
Return array of tuples device block ids, data block ids, addresses, and lengths to read from them to read the specified device offset & length. Note: data blocks may not amount to total requested length (if requesting data from unallocated space). @see DataMap#block?
[ "Return", "array", "of", "tuples", "device", "block", "ids", "data", "block", "ids", "addresses", "and", "lengths", "to", "read", "from", "them", "to", "read", "the", "specified", "device", "offset", "&", "length", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/VolumeManager/LVM/thin/superblock.rb#L89-L131
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/attrib_attribute_list.rb
NTFS.AttributeList.loadAttributes
def loadAttributes(attribType) result = [] # ad is an attribute descriptor. @list.each do |ad| next unless ad['attrib_type'] == attribType # Load referenced attribute and add it to parent. result += @boot_sector.mftEntry(ad['mft']).loadAttributes(attribType) end result end
ruby
def loadAttributes(attribType) result = [] # ad is an attribute descriptor. @list.each do |ad| next unless ad['attrib_type'] == attribType # Load referenced attribute and add it to parent. result += @boot_sector.mftEntry(ad['mft']).loadAttributes(attribType) end result end
[ "def", "loadAttributes", "(", "attribType", ")", "result", "=", "[", "]", "# ad is an attribute descriptor.", "@list", ".", "each", "do", "|", "ad", "|", "next", "unless", "ad", "[", "'attrib_type'", "]", "==", "attribType", "# Load referenced attribute and add it to parent.", "result", "+=", "@boot_sector", ".", "mftEntry", "(", "ad", "[", "'mft'", "]", ")", ".", "loadAttributes", "(", "attribType", ")", "end", "result", "end" ]
Load attributes of requested type
[ "Load", "attributes", "of", "requested", "type" ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/attrib_attribute_list.rb#L97-L109
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/attrib_data.rb
NTFS.AttribData.read
def read(bytes = @length) return nil if @pos >= @length bytes = @length - @pos if bytes.nil? bytes = @length - @pos if @pos + bytes > @length out = @data[@pos, bytes] if @data.kind_of?(String) out = @data.read(bytes) if @data.kind_of?(NTFS::DataRun) @pos += out.size out end
ruby
def read(bytes = @length) return nil if @pos >= @length bytes = @length - @pos if bytes.nil? bytes = @length - @pos if @pos + bytes > @length out = @data[@pos, bytes] if @data.kind_of?(String) out = @data.read(bytes) if @data.kind_of?(NTFS::DataRun) @pos += out.size out end
[ "def", "read", "(", "bytes", "=", "@length", ")", "return", "nil", "if", "@pos", ">=", "@length", "bytes", "=", "@length", "-", "@pos", "if", "bytes", ".", "nil?", "bytes", "=", "@length", "-", "@pos", "if", "@pos", "+", "bytes", ">", "@length", "out", "=", "@data", "[", "@pos", ",", "bytes", "]", "if", "@data", ".", "kind_of?", "(", "String", ")", "out", "=", "@data", ".", "read", "(", "bytes", ")", "if", "@data", ".", "kind_of?", "(", "NTFS", "::", "DataRun", ")", "@pos", "+=", "out", ".", "size", "out", "end" ]
This now behaves exactly like a normal read.
[ "This", "now", "behaves", "exactly", "like", "a", "normal", "read", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/attrib_data.rb#L41-L51
train
ManageIQ/manageiq-smartstate
lib/fs/fat32/boot_sect.rb
Fat32.BootSect.getNextCluster
def getNextCluster(clus) nxt = getFatEntry(clus) return nil if nxt > CC_END_OF_CHAIN raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED [nxt, getCluster(nxt)] end
ruby
def getNextCluster(clus) nxt = getFatEntry(clus) return nil if nxt > CC_END_OF_CHAIN raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED [nxt, getCluster(nxt)] end
[ "def", "getNextCluster", "(", "clus", ")", "nxt", "=", "getFatEntry", "(", "clus", ")", "return", "nil", "if", "nxt", ">", "CC_END_OF_CHAIN", "raise", "\"Damaged cluster in cluster chain\"", "if", "nxt", "==", "CC_DAMAGED", "[", "nxt", ",", "getCluster", "(", "nxt", ")", "]", "end" ]
Gets data for the next cluster given current, or nil if end.
[ "Gets", "data", "for", "the", "next", "cluster", "given", "current", "or", "nil", "if", "end", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/fat32/boot_sect.rb#L183-L188
train
ManageIQ/manageiq-smartstate
lib/fs/fat32/boot_sect.rb
Fat32.BootSect.countContigClusters
def countContigClusters(clus) cur = clus; nxt = 0 loop do nxt = getFatEntry(cur) break if nxt != cur + 1 cur = nxt; redo end raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED cur - clus + 1 end
ruby
def countContigClusters(clus) cur = clus; nxt = 0 loop do nxt = getFatEntry(cur) break if nxt != cur + 1 cur = nxt; redo end raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED cur - clus + 1 end
[ "def", "countContigClusters", "(", "clus", ")", "cur", "=", "clus", ";", "nxt", "=", "0", "loop", "do", "nxt", "=", "getFatEntry", "(", "cur", ")", "break", "if", "nxt", "!=", "cur", "+", "1", "cur", "=", "nxt", ";", "redo", "end", "raise", "\"Damaged cluster in cluster chain\"", "if", "nxt", "==", "CC_DAMAGED", "cur", "-", "clus", "+", "1", "end" ]
Count the number of continuous clusters from some beginning cluster.
[ "Count", "the", "number", "of", "continuous", "clusters", "from", "some", "beginning", "cluster", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/fat32/boot_sect.rb#L227-L236
train
ManageIQ/manageiq-smartstate
lib/fs/fat32/boot_sect.rb
Fat32.BootSect.wipeChain
def wipeChain(clus) loop do nxt = getFatEntry(clus) putFatEntry(clus, 0) break if nxt == 0 # A 0 entry means FAT is inconsistent. Chkdsk may report lost clusters. break if nxt == CC_DAMAGED # This should never happen but if it does allow clusters to become lost. break if nxt > CC_END_OF_CHAIN clus = nxt end end
ruby
def wipeChain(clus) loop do nxt = getFatEntry(clus) putFatEntry(clus, 0) break if nxt == 0 # A 0 entry means FAT is inconsistent. Chkdsk may report lost clusters. break if nxt == CC_DAMAGED # This should never happen but if it does allow clusters to become lost. break if nxt > CC_END_OF_CHAIN clus = nxt end end
[ "def", "wipeChain", "(", "clus", ")", "loop", "do", "nxt", "=", "getFatEntry", "(", "clus", ")", "putFatEntry", "(", "clus", ",", "0", ")", "break", "if", "nxt", "==", "0", "# A 0 entry means FAT is inconsistent. Chkdsk may report lost clusters.", "break", "if", "nxt", "==", "CC_DAMAGED", "# This should never happen but if it does allow clusters to become lost.", "break", "if", "nxt", ">", "CC_END_OF_CHAIN", "clus", "=", "nxt", "end", "end" ]
Deallocate all clusters on a chain from a starting cluster number.
[ "Deallocate", "all", "clusters", "on", "a", "chain", "from", "a", "starting", "cluster", "number", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/fat32/boot_sect.rb#L279-L288
train
ManageIQ/manageiq-smartstate
lib/fs/fat32/boot_sect.rb
Fat32.BootSect.writeClusters
def writeClusters(start, buf, len = buf.length) clus = start; num, leftover = len.divmod(@bytesPerCluster); num += 1 if leftover > 0 0.upto(num - 1) do |offset| local = buf[offset * @bytesPerCluster, @bytesPerCluster] if local.length < @bytesPerCluster then local += ("\0" * (@bytesPerCluster - local.length)) end @stream.seek(clusToByte(clus), IO::SEEK_SET) @stream.write(local, @bytesPerCluster) break if offset == num - 1 # ugly hack to prevent allocating more than needed. nxt = getFatEntry(clus) nxt = allocClusters(clus) if nxt > CC_END_OF_CHAIN clus = nxt end end
ruby
def writeClusters(start, buf, len = buf.length) clus = start; num, leftover = len.divmod(@bytesPerCluster); num += 1 if leftover > 0 0.upto(num - 1) do |offset| local = buf[offset * @bytesPerCluster, @bytesPerCluster] if local.length < @bytesPerCluster then local += ("\0" * (@bytesPerCluster - local.length)) end @stream.seek(clusToByte(clus), IO::SEEK_SET) @stream.write(local, @bytesPerCluster) break if offset == num - 1 # ugly hack to prevent allocating more than needed. nxt = getFatEntry(clus) nxt = allocClusters(clus) if nxt > CC_END_OF_CHAIN clus = nxt end end
[ "def", "writeClusters", "(", "start", ",", "buf", ",", "len", "=", "buf", ".", "length", ")", "clus", "=", "start", ";", "num", ",", "leftover", "=", "len", ".", "divmod", "(", "@bytesPerCluster", ")", ";", "num", "+=", "1", "if", "leftover", ">", "0", "0", ".", "upto", "(", "num", "-", "1", ")", "do", "|", "offset", "|", "local", "=", "buf", "[", "offset", "*", "@bytesPerCluster", ",", "@bytesPerCluster", "]", "if", "local", ".", "length", "<", "@bytesPerCluster", "then", "local", "+=", "(", "\"\\0\"", "*", "(", "@bytesPerCluster", "-", "local", ".", "length", ")", ")", "end", "@stream", ".", "seek", "(", "clusToByte", "(", "clus", ")", ",", "IO", "::", "SEEK_SET", ")", "@stream", ".", "write", "(", "local", ",", "@bytesPerCluster", ")", "break", "if", "offset", "==", "num", "-", "1", "# ugly hack to prevent allocating more than needed.", "nxt", "=", "getFatEntry", "(", "clus", ")", "nxt", "=", "allocClusters", "(", "clus", ")", "if", "nxt", ">", "CC_END_OF_CHAIN", "clus", "=", "nxt", "end", "end" ]
Start from defined cluster number and write data, following allocated cluster chain.
[ "Start", "from", "defined", "cluster", "number", "and", "write", "data", "following", "allocated", "cluster", "chain", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/fat32/boot_sect.rb#L291-L303
train
ManageIQ/manageiq-smartstate
lib/fs/fat32/boot_sect.rb
Fat32.BootSect.putFatEntry
def putFatEntry(clus, value) raise "DONT TOUCH THIS CLUSTER: #{clus}" if clus < 3 @stream.seek(@fatBase + FAT_ENTRY_SIZE * clus) @stream.write([value].pack('L'), FAT_ENTRY_SIZE) end
ruby
def putFatEntry(clus, value) raise "DONT TOUCH THIS CLUSTER: #{clus}" if clus < 3 @stream.seek(@fatBase + FAT_ENTRY_SIZE * clus) @stream.write([value].pack('L'), FAT_ENTRY_SIZE) end
[ "def", "putFatEntry", "(", "clus", ",", "value", ")", "raise", "\"DONT TOUCH THIS CLUSTER: #{clus}\"", "if", "clus", "<", "3", "@stream", ".", "seek", "(", "@fatBase", "+", "FAT_ENTRY_SIZE", "*", "clus", ")", "@stream", ".", "write", "(", "[", "value", "]", ".", "pack", "(", "'L'", ")", ",", "FAT_ENTRY_SIZE", ")", "end" ]
Write a FAT entry for a cluster.
[ "Write", "a", "FAT", "entry", "for", "a", "cluster", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/fat32/boot_sect.rb#L318-L322
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/boot_sect.rb
NTFS.BootSect.clusterInfo
def clusterInfo return @clusterInfo unless @clusterInfo.nil? # MFT Entry 6 ==> BITMAP Information ad = mftEntry(6).attributeData data = ad.read(ad.length) ad.rewind c = data.unpack("b#{data.length * 8}")[0] nclusters = c.length on = c.count("1") uclusters = on fclusters = c.length - on @clusterInfo = {"total" => nclusters, "free" => fclusters, "used" => uclusters} end
ruby
def clusterInfo return @clusterInfo unless @clusterInfo.nil? # MFT Entry 6 ==> BITMAP Information ad = mftEntry(6).attributeData data = ad.read(ad.length) ad.rewind c = data.unpack("b#{data.length * 8}")[0] nclusters = c.length on = c.count("1") uclusters = on fclusters = c.length - on @clusterInfo = {"total" => nclusters, "free" => fclusters, "used" => uclusters} end
[ "def", "clusterInfo", "return", "@clusterInfo", "unless", "@clusterInfo", ".", "nil?", "# MFT Entry 6 ==> BITMAP Information", "ad", "=", "mftEntry", "(", "6", ")", ".", "attributeData", "data", "=", "ad", ".", "read", "(", "ad", ".", "length", ")", "ad", ".", "rewind", "c", "=", "data", ".", "unpack", "(", "\"b#{data.length * 8}\"", ")", "[", "0", "]", "nclusters", "=", "c", ".", "length", "on", "=", "c", ".", "count", "(", "\"1\"", ")", "uclusters", "=", "on", "fclusters", "=", "c", ".", "length", "-", "on", "@clusterInfo", "=", "{", "\"total\"", "=>", "nclusters", ",", "\"free\"", "=>", "fclusters", ",", "\"used\"", "=>", "uclusters", "}", "end" ]
From "File System Forensic Analysis" by Brian Carrier The $Bitmap file, which is located in MFT entry 6, has a $DATA attribute that is used to manage the allocation status of clusters. The bitmap data are organized into 1-byte values, and the least significant bit of each byte corresponds to the cluster that follows the cluster that the most significant bit of the previous byte corresponds to.
[ "From", "File", "System", "Forensic", "Analysis", "by", "Brian", "Carrier" ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/boot_sect.rb#L135-L150
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/boot_sect.rb
NTFS.BootSect.mftRecToBytePos
def mftRecToBytePos(recno) # Return start of mft if rec 0 (no point in the rest of this). return mftLoc if recno == 0 # Find which fragment contains the target mft record. start = fragTable[0]; last_clusters = 0; target_cluster = recno * @bytesPerFileRec / @bytesPerCluster if (recno > @bytesPerCluster / @bytesPerFileRec) && (fragTable.size > 2) total_clusters = 0 fragTable.each_slice(2) do |vcn, len| start = vcn # These are now absolute clusters, not offsets. total_clusters += len break if total_clusters > target_cluster last_clusters += len end # Toss if we haven't found the fragment. raise "MIQ(NTFS::BootSect.mftRecToBytePos) Can't find MFT record #{recno} in data run.\ntarget = #{target_cluster}\ntbl = #{fragTable.inspect}" if total_clusters < target_cluster end # Calculate offset in target cluster & final byte position. offset = (recno - (last_clusters * @bytesPerCluster / @bytesPerFileRec)) * @bytesPerFileRec start * @bytesPerCluster + offset end
ruby
def mftRecToBytePos(recno) # Return start of mft if rec 0 (no point in the rest of this). return mftLoc if recno == 0 # Find which fragment contains the target mft record. start = fragTable[0]; last_clusters = 0; target_cluster = recno * @bytesPerFileRec / @bytesPerCluster if (recno > @bytesPerCluster / @bytesPerFileRec) && (fragTable.size > 2) total_clusters = 0 fragTable.each_slice(2) do |vcn, len| start = vcn # These are now absolute clusters, not offsets. total_clusters += len break if total_clusters > target_cluster last_clusters += len end # Toss if we haven't found the fragment. raise "MIQ(NTFS::BootSect.mftRecToBytePos) Can't find MFT record #{recno} in data run.\ntarget = #{target_cluster}\ntbl = #{fragTable.inspect}" if total_clusters < target_cluster end # Calculate offset in target cluster & final byte position. offset = (recno - (last_clusters * @bytesPerCluster / @bytesPerFileRec)) * @bytesPerFileRec start * @bytesPerCluster + offset end
[ "def", "mftRecToBytePos", "(", "recno", ")", "# Return start of mft if rec 0 (no point in the rest of this).", "return", "mftLoc", "if", "recno", "==", "0", "# Find which fragment contains the target mft record.", "start", "=", "fragTable", "[", "0", "]", ";", "last_clusters", "=", "0", ";", "target_cluster", "=", "recno", "*", "@bytesPerFileRec", "/", "@bytesPerCluster", "if", "(", "recno", ">", "@bytesPerCluster", "/", "@bytesPerFileRec", ")", "&&", "(", "fragTable", ".", "size", ">", "2", ")", "total_clusters", "=", "0", "fragTable", ".", "each_slice", "(", "2", ")", "do", "|", "vcn", ",", "len", "|", "start", "=", "vcn", "# These are now absolute clusters, not offsets.", "total_clusters", "+=", "len", "break", "if", "total_clusters", ">", "target_cluster", "last_clusters", "+=", "len", "end", "# Toss if we haven't found the fragment.", "raise", "\"MIQ(NTFS::BootSect.mftRecToBytePos) Can't find MFT record #{recno} in data run.\\ntarget = #{target_cluster}\\ntbl = #{fragTable.inspect}\"", "if", "total_clusters", "<", "target_cluster", "end", "# Calculate offset in target cluster & final byte position.", "offset", "=", "(", "recno", "-", "(", "last_clusters", "*", "@bytesPerCluster", "/", "@bytesPerFileRec", ")", ")", "*", "@bytesPerFileRec", "start", "*", "@bytesPerCluster", "+", "offset", "end" ]
Use data run to convert mft record number to byte pos.
[ "Use", "data", "run", "to", "convert", "mft", "record", "number", "to", "byte", "pos", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/boot_sect.rb#L230-L251
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/directory_index_node.rb
NTFS.DirectoryIndexNode.dump
def dump out = "\#<#{self.class}:0x#{'%08x' % object_id}>\n" out << " Mft Ref : seq #{@refMft[0]}, entry #{@refMft[1]}\n" out << " Length : #{@length}\n" out << " Content : #{@contentLen}\n" out << " Flags : 0x#{'%08x' % @flags}\n" out << @afn.dump if @contentLen > 0 out << " Child ref: #{@child}\n" if NTFS::Utils.gotBit?(@flags, IN_HAS_CHILD) out << "---\n" end
ruby
def dump out = "\#<#{self.class}:0x#{'%08x' % object_id}>\n" out << " Mft Ref : seq #{@refMft[0]}, entry #{@refMft[1]}\n" out << " Length : #{@length}\n" out << " Content : #{@contentLen}\n" out << " Flags : 0x#{'%08x' % @flags}\n" out << @afn.dump if @contentLen > 0 out << " Child ref: #{@child}\n" if NTFS::Utils.gotBit?(@flags, IN_HAS_CHILD) out << "---\n" end
[ "def", "dump", "out", "=", "\"\\#<#{self.class}:0x#{'%08x' % object_id}>\\n\"", "out", "<<", "\" Mft Ref : seq #{@refMft[0]}, entry #{@refMft[1]}\\n\"", "out", "<<", "\" Length : #{@length}\\n\"", "out", "<<", "\" Content : #{@contentLen}\\n\"", "out", "<<", "\" Flags : 0x#{'%08x' % @flags}\\n\"", "out", "<<", "@afn", ".", "dump", "if", "@contentLen", ">", "0", "out", "<<", "\" Child ref: #{@child}\\n\"", "if", "NTFS", "::", "Utils", ".", "gotBit?", "(", "@flags", ",", "IN_HAS_CHILD", ")", "out", "<<", "\"---\\n\"", "end" ]
Dumps object.
[ "Dumps", "object", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/directory_index_node.rb#L99-L108
train
ManageIQ/manageiq-smartstate
lib/fs/ext4/directory.rb
Ext4.Directory.globEntriesByHashTree
def globEntriesByHashTree ents_by_name = {} offset = 0 # Chomp fake '.' and '..' directories first 2.times do de = DirectoryEntry.new(@data[offset..-1], @sb.isNewDirEnt?) ents_by_name[de.name] ||= [] ents_by_name[de.name] << de offset += 12 end $log.info("Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) >>\n#{@data[0, 256].hex_dump}") header = HashTreeHeader.new(@data[offset..-1]) $log.info("Ext4::Directory.globEntriesByHashTree --\n#{header.dump}") $log.info("Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) <<#{ents_by_name.inspect}") offset += header.length root = HashTreeEntry.new(@data[offset..-1], true) $log.info("Ext4::Directory.globEntriesByHashTree --\n#{root.dump}") ents_by_name end
ruby
def globEntriesByHashTree ents_by_name = {} offset = 0 # Chomp fake '.' and '..' directories first 2.times do de = DirectoryEntry.new(@data[offset..-1], @sb.isNewDirEnt?) ents_by_name[de.name] ||= [] ents_by_name[de.name] << de offset += 12 end $log.info("Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) >>\n#{@data[0, 256].hex_dump}") header = HashTreeHeader.new(@data[offset..-1]) $log.info("Ext4::Directory.globEntriesByHashTree --\n#{header.dump}") $log.info("Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) <<#{ents_by_name.inspect}") offset += header.length root = HashTreeEntry.new(@data[offset..-1], true) $log.info("Ext4::Directory.globEntriesByHashTree --\n#{root.dump}") ents_by_name end
[ "def", "globEntriesByHashTree", "ents_by_name", "=", "{", "}", "offset", "=", "0", "# Chomp fake '.' and '..' directories first", "2", ".", "times", "do", "de", "=", "DirectoryEntry", ".", "new", "(", "@data", "[", "offset", "..", "-", "1", "]", ",", "@sb", ".", "isNewDirEnt?", ")", "ents_by_name", "[", "de", ".", "name", "]", "||=", "[", "]", "ents_by_name", "[", "de", ".", "name", "]", "<<", "de", "offset", "+=", "12", "end", "$log", ".", "info", "(", "\"Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) >>\\n#{@data[0, 256].hex_dump}\"", ")", "header", "=", "HashTreeHeader", ".", "new", "(", "@data", "[", "offset", "..", "-", "1", "]", ")", "$log", ".", "info", "(", "\"Ext4::Directory.globEntriesByHashTree --\\n#{header.dump}\"", ")", "$log", ".", "info", "(", "\"Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) <<#{ents_by_name.inspect}\"", ")", "offset", "+=", "header", ".", "length", "root", "=", "HashTreeEntry", ".", "new", "(", "@data", "[", "offset", "..", "-", "1", "]", ",", "true", ")", "$log", ".", "info", "(", "\"Ext4::Directory.globEntriesByHashTree --\\n#{root.dump}\"", ")", "ents_by_name", "end" ]
If the inode has the IF_HASH_INDEX bit set, then the first directory block is to be interpreted as the root of an HTree index.
[ "If", "the", "inode", "has", "the", "IF_HASH_INDEX", "bit", "set", "then", "the", "first", "directory", "block", "is", "to", "be", "interpreted", "as", "the", "root", "of", "an", "HTree", "index", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ext4/directory.rb#L66-L85
train
ManageIQ/manageiq-smartstate
lib/db/MiqBdb/MiqBdbPage.rb
MiqBerkeleyDB.MiqBdbPage.dump
def dump out = "" out << "Page #{current}\n" out << " type: #{MiqBdbPage.type2string(ptype)}\n" out << " prev: #{prev}\n" out << " next: #{@header['next_pgno']}\n" out << " log seq num: file=#{@header['lsn_file']} offset=#{@header['lsn_offset']}\n" out << " level: #{level}\n" if @header['p_type'] == P_OVERFLOW out << " ref cnt: #{nentries}\n" out << " len: #{offset}\n" else out << " entries: #{nentries}\n" out << " offset: #{offset}\n" end out << " data size: #{@data.size}\n" out << " data: " @data.bytes.take(20).each do |c| out << sprintf("%.2x ", c) end out << "..." if @data.size > 20 out << "\n\n" out end
ruby
def dump out = "" out << "Page #{current}\n" out << " type: #{MiqBdbPage.type2string(ptype)}\n" out << " prev: #{prev}\n" out << " next: #{@header['next_pgno']}\n" out << " log seq num: file=#{@header['lsn_file']} offset=#{@header['lsn_offset']}\n" out << " level: #{level}\n" if @header['p_type'] == P_OVERFLOW out << " ref cnt: #{nentries}\n" out << " len: #{offset}\n" else out << " entries: #{nentries}\n" out << " offset: #{offset}\n" end out << " data size: #{@data.size}\n" out << " data: " @data.bytes.take(20).each do |c| out << sprintf("%.2x ", c) end out << "..." if @data.size > 20 out << "\n\n" out end
[ "def", "dump", "out", "=", "\"\"", "out", "<<", "\"Page #{current}\\n\"", "out", "<<", "\" type: #{MiqBdbPage.type2string(ptype)}\\n\"", "out", "<<", "\" prev: #{prev}\\n\"", "out", "<<", "\" next: #{@header['next_pgno']}\\n\"", "out", "<<", "\" log seq num: file=#{@header['lsn_file']} offset=#{@header['lsn_offset']}\\n\"", "out", "<<", "\" level: #{level}\\n\"", "if", "@header", "[", "'p_type'", "]", "==", "P_OVERFLOW", "out", "<<", "\" ref cnt: #{nentries}\\n\"", "out", "<<", "\" len: #{offset}\\n\"", "else", "out", "<<", "\" entries: #{nentries}\\n\"", "out", "<<", "\" offset: #{offset}\\n\"", "end", "out", "<<", "\" data size: #{@data.size}\\n\"", "out", "<<", "\" data: \"", "@data", ".", "bytes", ".", "take", "(", "20", ")", ".", "each", "do", "|", "c", "|", "out", "<<", "sprintf", "(", "\"%.2x \"", ",", "c", ")", "end", "out", "<<", "\"...\"", "if", "@data", ".", "size", ">", "20", "out", "<<", "\"\\n\\n\"", "out", "end" ]
Dump page statistics like db_dump.
[ "Dump", "page", "statistics", "like", "db_dump", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/db/MiqBdb/MiqBdbPage.rb#L131-L157
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/attrib_index_root.rb
NTFS.IndexRoot.find
def find(name) log_prefix = "MIQ(NTFS::IndexRoot.find)" name = name.downcase $log.debug "#{log_prefix} Searching for [#{name}]" if DEBUG_TRACE_FIND if @foundEntries.key?(name) $log.debug "#{log_prefix} Found [#{name}] (cached)" if DEBUG_TRACE_FIND return @foundEntries[name] end found = findInEntries(name, @indexEntries) if found.nil? # Fallback to full directory search if not found $log.debug "#{log_prefix} [#{name}] not found. Performing full directory scan." if $log found = findBackup(name) $log.send(found.nil? ? :debug : :warn, "#{log_prefix} [#{name}] #{found.nil? ? "not " : ""}found in full directory scan.") if $log end found end
ruby
def find(name) log_prefix = "MIQ(NTFS::IndexRoot.find)" name = name.downcase $log.debug "#{log_prefix} Searching for [#{name}]" if DEBUG_TRACE_FIND if @foundEntries.key?(name) $log.debug "#{log_prefix} Found [#{name}] (cached)" if DEBUG_TRACE_FIND return @foundEntries[name] end found = findInEntries(name, @indexEntries) if found.nil? # Fallback to full directory search if not found $log.debug "#{log_prefix} [#{name}] not found. Performing full directory scan." if $log found = findBackup(name) $log.send(found.nil? ? :debug : :warn, "#{log_prefix} [#{name}] #{found.nil? ? "not " : ""}found in full directory scan.") if $log end found end
[ "def", "find", "(", "name", ")", "log_prefix", "=", "\"MIQ(NTFS::IndexRoot.find)\"", "name", "=", "name", ".", "downcase", "$log", ".", "debug", "\"#{log_prefix} Searching for [#{name}]\"", "if", "DEBUG_TRACE_FIND", "if", "@foundEntries", ".", "key?", "(", "name", ")", "$log", ".", "debug", "\"#{log_prefix} Found [#{name}] (cached)\"", "if", "DEBUG_TRACE_FIND", "return", "@foundEntries", "[", "name", "]", "end", "found", "=", "findInEntries", "(", "name", ",", "@indexEntries", ")", "if", "found", ".", "nil?", "# Fallback to full directory search if not found", "$log", ".", "debug", "\"#{log_prefix} [#{name}] not found. Performing full directory scan.\"", "if", "$log", "found", "=", "findBackup", "(", "name", ")", "$log", ".", "send", "(", "found", ".", "nil?", "?", ":debug", ":", ":warn", ",", "\"#{log_prefix} [#{name}] #{found.nil? ? \"not \" : \"\"}found in full directory scan.\"", ")", "if", "$log", "end", "found", "end" ]
Find a name in this index.
[ "Find", "a", "name", "in", "this", "index", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/attrib_index_root.rb#L106-L124
train
ManageIQ/manageiq-smartstate
lib/fs/ntfs/attrib_index_root.rb
NTFS.IndexRoot.globNames
def globNames @globNames = globEntries.collect { |e| e.namespace == NTFS::FileName::NS_DOS ? nil : e.name.downcase }.compact if @globNames.nil? @globNames end
ruby
def globNames @globNames = globEntries.collect { |e| e.namespace == NTFS::FileName::NS_DOS ? nil : e.name.downcase }.compact if @globNames.nil? @globNames end
[ "def", "globNames", "@globNames", "=", "globEntries", ".", "collect", "{", "|", "e", "|", "e", ".", "namespace", "==", "NTFS", "::", "FileName", "::", "NS_DOS", "?", "nil", ":", "e", ".", "name", ".", "downcase", "}", ".", "compact", "if", "@globNames", ".", "nil?", "@globNames", "end" ]
Return all names in this index as a sorted string array.
[ "Return", "all", "names", "in", "this", "index", "as", "a", "sorted", "string", "array", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ntfs/attrib_index_root.rb#L127-L130
train
ManageIQ/manageiq-smartstate
lib/fs/ReiserFS/block.rb
ReiserFS.Block.getKey
def getKey(k) return nil if k > @nitems || k <= 0 pos = SIZEOF_BLOCK_HEADER + (SIZEOF_KEY * (k - 1)) keydata = @data[pos, SIZEOF_KEY] data2key(keydata) end
ruby
def getKey(k) return nil if k > @nitems || k <= 0 pos = SIZEOF_BLOCK_HEADER + (SIZEOF_KEY * (k - 1)) keydata = @data[pos, SIZEOF_KEY] data2key(keydata) end
[ "def", "getKey", "(", "k", ")", "return", "nil", "if", "k", ">", "@nitems", "||", "k", "<=", "0", "pos", "=", "SIZEOF_BLOCK_HEADER", "+", "(", "SIZEOF_KEY", "*", "(", "k", "-", "1", ")", ")", "keydata", "=", "@data", "[", "pos", ",", "SIZEOF_KEY", "]", "data2key", "(", "keydata", ")", "end" ]
Keys are 1-based
[ "Keys", "are", "1", "-", "based" ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ReiserFS/block.rb#L50-L55
train
ManageIQ/manageiq-smartstate
lib/fs/ReiserFS/block.rb
ReiserFS.Block.getPointer
def getPointer(p) # puts "getPointer >> p=#{p}" return nil if p > @nitems || p < 0 pos = SIZEOF_BLOCK_HEADER + (SIZEOF_KEY * @nitems) + (SIZEOF_POINTER * p) ptrdata = @data[pos, SIZEOF_POINTER] POINTER.decode(ptrdata) end
ruby
def getPointer(p) # puts "getPointer >> p=#{p}" return nil if p > @nitems || p < 0 pos = SIZEOF_BLOCK_HEADER + (SIZEOF_KEY * @nitems) + (SIZEOF_POINTER * p) ptrdata = @data[pos, SIZEOF_POINTER] POINTER.decode(ptrdata) end
[ "def", "getPointer", "(", "p", ")", "# puts \"getPointer >> p=#{p}\"", "return", "nil", "if", "p", ">", "@nitems", "||", "p", "<", "0", "pos", "=", "SIZEOF_BLOCK_HEADER", "+", "(", "SIZEOF_KEY", "*", "@nitems", ")", "+", "(", "SIZEOF_POINTER", "*", "p", ")", "ptrdata", "=", "@data", "[", "pos", ",", "SIZEOF_POINTER", "]", "POINTER", ".", "decode", "(", "ptrdata", ")", "end" ]
Pointers are 0-based
[ "Pointers", "are", "0", "-", "based" ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/ReiserFS/block.rb#L65-L71
train
ManageIQ/manageiq-smartstate
lib/fs/iso9660/boot_sector.rb
Iso9660.BootSector.dump
def dump out = "\n" out += "Type : #{@bs['desc_type']}\n" out += "Record ID : #{@bs['id']}\n" out += "Version : #{@bs['version']}\n" out += "System ID : #{@bs['system_id'].strip}\n" out += "Volume ID : #{@volName}\n" out += "Vol space size : #{@bs["vol_space_size#{@suff}"]} (sectors)\n" out += "Vol set size : #{@bs["vol_set_size#{@suff}"]}\n" out += "Vol sequence num: #{@bs["vol_seq_number#{@suff}"]}\n" out += "Logical blk size: #{@bs["log_block_size#{@suff}"]} (sector size)\n" out += "Path table size : #{@bs["path_table_size#{@suff}"]}\n" out += "Type 1 path tbl : #{@bs["type_1_path_table#{@suff}"]}\n" out += "Opt type 1 pth : #{@bs["opt_type_1_path_table#{@suff}"]}\n" out += "Type M path tbl : #{@bs["type_m_path_table#{@suff}"]}\n" out += "Opt type M pth : #{@bs["opt_type_m_path_table#{@suff}"]}\n" out += "Vol set ID : #{@bs['vol_set_id'].strip}\n" out += "Publisher ID : #{@bs['publisher_id'].strip}\n" out += "Preparer ID : #{@bs['preparer_id'].strip}\n" out += "Application ID : #{@bs['application_id'].strip}\n" out += "Copyright : #{@bs['copyright_file_id'].strip}\n" out += "Abstract : #{@bs['abstract_file_id'].strip}\n" out += "Biblographic : #{@bs['biblographic_file_id'].strip}\n" out += "Creation date : #{@bs['creation_date'].strip} (#{@cTime}, tz = #{Util.GetTimezone(@bs['creation_date'])})\n" out += "Mod date : #{@bs['modification_date'].strip} (#{@mTime}, tz = #{Util.GetTimezone(@bs['modification_date'])})\n" out += "Expiration date : #{@bs['experation_date'].strip} (#{@expirationDate}, tz = #{Util.GetTimezone(@bs['experation_date'])})\n" out += "Effective date : #{@bs['effective_date'].strip} (#{@effectiveDate}, tz = #{Util.GetTimezone(@bs['effective_date'])})\n" out += "File strct ver : #{@bs['file_structure_version']}\n" out += "Application data: #{@bs['application_data'].strip}\n" end
ruby
def dump out = "\n" out += "Type : #{@bs['desc_type']}\n" out += "Record ID : #{@bs['id']}\n" out += "Version : #{@bs['version']}\n" out += "System ID : #{@bs['system_id'].strip}\n" out += "Volume ID : #{@volName}\n" out += "Vol space size : #{@bs["vol_space_size#{@suff}"]} (sectors)\n" out += "Vol set size : #{@bs["vol_set_size#{@suff}"]}\n" out += "Vol sequence num: #{@bs["vol_seq_number#{@suff}"]}\n" out += "Logical blk size: #{@bs["log_block_size#{@suff}"]} (sector size)\n" out += "Path table size : #{@bs["path_table_size#{@suff}"]}\n" out += "Type 1 path tbl : #{@bs["type_1_path_table#{@suff}"]}\n" out += "Opt type 1 pth : #{@bs["opt_type_1_path_table#{@suff}"]}\n" out += "Type M path tbl : #{@bs["type_m_path_table#{@suff}"]}\n" out += "Opt type M pth : #{@bs["opt_type_m_path_table#{@suff}"]}\n" out += "Vol set ID : #{@bs['vol_set_id'].strip}\n" out += "Publisher ID : #{@bs['publisher_id'].strip}\n" out += "Preparer ID : #{@bs['preparer_id'].strip}\n" out += "Application ID : #{@bs['application_id'].strip}\n" out += "Copyright : #{@bs['copyright_file_id'].strip}\n" out += "Abstract : #{@bs['abstract_file_id'].strip}\n" out += "Biblographic : #{@bs['biblographic_file_id'].strip}\n" out += "Creation date : #{@bs['creation_date'].strip} (#{@cTime}, tz = #{Util.GetTimezone(@bs['creation_date'])})\n" out += "Mod date : #{@bs['modification_date'].strip} (#{@mTime}, tz = #{Util.GetTimezone(@bs['modification_date'])})\n" out += "Expiration date : #{@bs['experation_date'].strip} (#{@expirationDate}, tz = #{Util.GetTimezone(@bs['experation_date'])})\n" out += "Effective date : #{@bs['effective_date'].strip} (#{@effectiveDate}, tz = #{Util.GetTimezone(@bs['effective_date'])})\n" out += "File strct ver : #{@bs['file_structure_version']}\n" out += "Application data: #{@bs['application_data'].strip}\n" end
[ "def", "dump", "out", "=", "\"\\n\"", "out", "+=", "\"Type : #{@bs['desc_type']}\\n\"", "out", "+=", "\"Record ID : #{@bs['id']}\\n\"", "out", "+=", "\"Version : #{@bs['version']}\\n\"", "out", "+=", "\"System ID : #{@bs['system_id'].strip}\\n\"", "out", "+=", "\"Volume ID : #{@volName}\\n\"", "out", "+=", "\"Vol space size : #{@bs[\"vol_space_size#{@suff}\"]} (sectors)\\n\"", "out", "+=", "\"Vol set size : #{@bs[\"vol_set_size#{@suff}\"]}\\n\"", "out", "+=", "\"Vol sequence num: #{@bs[\"vol_seq_number#{@suff}\"]}\\n\"", "out", "+=", "\"Logical blk size: #{@bs[\"log_block_size#{@suff}\"]} (sector size)\\n\"", "out", "+=", "\"Path table size : #{@bs[\"path_table_size#{@suff}\"]}\\n\"", "out", "+=", "\"Type 1 path tbl : #{@bs[\"type_1_path_table#{@suff}\"]}\\n\"", "out", "+=", "\"Opt type 1 pth : #{@bs[\"opt_type_1_path_table#{@suff}\"]}\\n\"", "out", "+=", "\"Type M path tbl : #{@bs[\"type_m_path_table#{@suff}\"]}\\n\"", "out", "+=", "\"Opt type M pth : #{@bs[\"opt_type_m_path_table#{@suff}\"]}\\n\"", "out", "+=", "\"Vol set ID : #{@bs['vol_set_id'].strip}\\n\"", "out", "+=", "\"Publisher ID : #{@bs['publisher_id'].strip}\\n\"", "out", "+=", "\"Preparer ID : #{@bs['preparer_id'].strip}\\n\"", "out", "+=", "\"Application ID : #{@bs['application_id'].strip}\\n\"", "out", "+=", "\"Copyright : #{@bs['copyright_file_id'].strip}\\n\"", "out", "+=", "\"Abstract : #{@bs['abstract_file_id'].strip}\\n\"", "out", "+=", "\"Biblographic : #{@bs['biblographic_file_id'].strip}\\n\"", "out", "+=", "\"Creation date : #{@bs['creation_date'].strip} (#{@cTime}, tz = #{Util.GetTimezone(@bs['creation_date'])})\\n\"", "out", "+=", "\"Mod date : #{@bs['modification_date'].strip} (#{@mTime}, tz = #{Util.GetTimezone(@bs['modification_date'])})\\n\"", "out", "+=", "\"Expiration date : #{@bs['experation_date'].strip} (#{@expirationDate}, tz = #{Util.GetTimezone(@bs['experation_date'])})\\n\"", "out", "+=", "\"Effective date : #{@bs['effective_date'].strip} (#{@effectiveDate}, tz = #{Util.GetTimezone(@bs['effective_date'])})\\n\"", "out", "+=", "\"File strct ver : #{@bs['file_structure_version']}\\n\"", "out", "+=", "\"Application data: #{@bs['application_data'].strip}\\n\"", "end" ]
This is a raw dump with no character set conversion.
[ "This", "is", "a", "raw", "dump", "with", "no", "character", "set", "conversion", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/iso9660/boot_sector.rb#L140-L169
train
ManageIQ/manageiq-smartstate
lib/fs/xfs/inode.rb
XFS.Inode.bmap_btree_record_to_block_pointers
def bmap_btree_record_to_block_pointers(record, block_pointers_length) block_pointers = [] # Fill in the missing blocks with 0-blocks block_pointers << 0 while (block_pointers_length + block_pointers.length) < record.start_offset 1.upto(record.block_count) { |i| block_pointers << record.start_block + i - 1 } @block_offset += record.block_count block_pointers end
ruby
def bmap_btree_record_to_block_pointers(record, block_pointers_length) block_pointers = [] # Fill in the missing blocks with 0-blocks block_pointers << 0 while (block_pointers_length + block_pointers.length) < record.start_offset 1.upto(record.block_count) { |i| block_pointers << record.start_block + i - 1 } @block_offset += record.block_count block_pointers end
[ "def", "bmap_btree_record_to_block_pointers", "(", "record", ",", "block_pointers_length", ")", "block_pointers", "=", "[", "]", "# Fill in the missing blocks with 0-blocks", "block_pointers", "<<", "0", "while", "(", "block_pointers_length", "+", "block_pointers", ".", "length", ")", "<", "record", ".", "start_offset", "1", ".", "upto", "(", "record", ".", "block_count", ")", "{", "|", "i", "|", "block_pointers", "<<", "record", ".", "start_block", "+", "i", "-", "1", "}", "@block_offset", "+=", "record", ".", "block_count", "block_pointers", "end" ]
This method is used for both extents and BTree leaf nodes
[ "This", "method", "is", "used", "for", "both", "extents", "and", "BTree", "leaf", "nodes" ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/fs/xfs/inode.rb#L428-L435
train
ManageIQ/manageiq-smartstate
lib/metadata/linux/LinuxPackages.rb
MiqLinux.Packages.procRPM
def procRPM(dbDir) $log.debug "Processing RPM package database" rpmp = MiqRpmPackages.new(@fs, File.join(dbDir, "Packages")) rpmp.each { |p| @packages << p } rpmp.close end
ruby
def procRPM(dbDir) $log.debug "Processing RPM package database" rpmp = MiqRpmPackages.new(@fs, File.join(dbDir, "Packages")) rpmp.each { |p| @packages << p } rpmp.close end
[ "def", "procRPM", "(", "dbDir", ")", "$log", ".", "debug", "\"Processing RPM package database\"", "rpmp", "=", "MiqRpmPackages", ".", "new", "(", "@fs", ",", "File", ".", "join", "(", "dbDir", ",", "\"Packages\"", ")", ")", "rpmp", ".", "each", "{", "|", "p", "|", "@packages", "<<", "p", "}", "rpmp", ".", "close", "end" ]
Client-side RPM DB processing.
[ "Client", "-", "side", "RPM", "DB", "processing", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/metadata/linux/LinuxPackages.rb#L155-L160
train
ManageIQ/manageiq-smartstate
lib/metadata/linux/LinuxPackages.rb
MiqLinux.Packages.procConary
def procConary(dbFile) $log.debug "Processing Conary package database" rpmp = MiqConaryPackages.new(@fs, dbFile) rpmp.each { |p| @packages << p } rpmp.close end
ruby
def procConary(dbFile) $log.debug "Processing Conary package database" rpmp = MiqConaryPackages.new(@fs, dbFile) rpmp.each { |p| @packages << p } rpmp.close end
[ "def", "procConary", "(", "dbFile", ")", "$log", ".", "debug", "\"Processing Conary package database\"", "rpmp", "=", "MiqConaryPackages", ".", "new", "(", "@fs", ",", "dbFile", ")", "rpmp", ".", "each", "{", "|", "p", "|", "@packages", "<<", "p", "}", "rpmp", ".", "close", "end" ]
Conary DB processing
[ "Conary", "DB", "processing" ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/metadata/linux/LinuxPackages.rb#L165-L170
train
ManageIQ/manageiq-smartstate
lib/metadata/util/win32/Win32System.rb
MiqWin32.System.os_product_suite
def os_product_suite(hash) eid = hash.delete(:edition_id) ps = hash.delete(:product_suite) # If edition_id is populated then the edition will already be part of the product_name string if eid.nil? && !hash[:product_name].nil? ps = ps.to_s.split("\n") if ps.length > 1 && !hash[:product_name].include?(ps.first) hash[:product_name] = "#{hash[:product_name].strip} #{ps.first} Edition" end end end
ruby
def os_product_suite(hash) eid = hash.delete(:edition_id) ps = hash.delete(:product_suite) # If edition_id is populated then the edition will already be part of the product_name string if eid.nil? && !hash[:product_name].nil? ps = ps.to_s.split("\n") if ps.length > 1 && !hash[:product_name].include?(ps.first) hash[:product_name] = "#{hash[:product_name].strip} #{ps.first} Edition" end end end
[ "def", "os_product_suite", "(", "hash", ")", "eid", "=", "hash", ".", "delete", "(", ":edition_id", ")", "ps", "=", "hash", ".", "delete", "(", ":product_suite", ")", "# If edition_id is populated then the edition will already be part of the product_name string", "if", "eid", ".", "nil?", "&&", "!", "hash", "[", ":product_name", "]", ".", "nil?", "ps", "=", "ps", ".", "to_s", ".", "split", "(", "\"\\n\"", ")", "if", "ps", ".", "length", ">", "1", "&&", "!", "hash", "[", ":product_name", "]", ".", "include?", "(", "ps", ".", "first", ")", "hash", "[", ":product_name", "]", "=", "\"#{hash[:product_name].strip} #{ps.first} Edition\"", "end", "end", "end" ]
Parse product edition and append to product_name if needed.
[ "Parse", "product", "edition", "and", "append", "to", "product_name", "if", "needed", "." ]
88fed6e9e6c0b69e87d71d1912c77aca535f7caa
https://github.com/ManageIQ/manageiq-smartstate/blob/88fed6e9e6c0b69e87d71d1912c77aca535f7caa/lib/metadata/util/win32/Win32System.rb#L237-L248
train
leikind/wice_grid
lib/wice/grid_output_buffer.rb
Wice.GridOutputBuffer.add_filter
def add_filter(detach_with_id, filter_code) raise WiceGridException.new("Detached ID #{detach_with_id} is already used!") if @filters.key? detach_with_id @filters[detach_with_id] = filter_code end
ruby
def add_filter(detach_with_id, filter_code) raise WiceGridException.new("Detached ID #{detach_with_id} is already used!") if @filters.key? detach_with_id @filters[detach_with_id] = filter_code end
[ "def", "add_filter", "(", "detach_with_id", ",", "filter_code", ")", "raise", "WiceGridException", ".", "new", "(", "\"Detached ID #{detach_with_id} is already used!\"", ")", "if", "@filters", ".", "key?", "detach_with_id", "@filters", "[", "detach_with_id", "]", "=", "filter_code", "end" ]
stores HTML code for a detached filter
[ "stores", "HTML", "code", "for", "a", "detached", "filter" ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/grid_output_buffer.rb#L21-L24
train
leikind/wice_grid
lib/wice/grid_output_buffer.rb
Wice.GridOutputBuffer.filter_for
def filter_for(detach_with_id) unless @filters.key? detach_with_id if @return_empty_strings_for_nonexistent_filters return '' else raise WiceGridException.new("No filter with Detached ID '#{detach_with_id}'!") end end unless @filters[detach_with_id] raise WiceGridException.new("Filter with Detached ID '#{detach_with_id}' has already been requested once! There cannot be two instances of the same filter on one page") end res = @filters[detach_with_id] @filters[detach_with_id] = false res end
ruby
def filter_for(detach_with_id) unless @filters.key? detach_with_id if @return_empty_strings_for_nonexistent_filters return '' else raise WiceGridException.new("No filter with Detached ID '#{detach_with_id}'!") end end unless @filters[detach_with_id] raise WiceGridException.new("Filter with Detached ID '#{detach_with_id}' has already been requested once! There cannot be two instances of the same filter on one page") end res = @filters[detach_with_id] @filters[detach_with_id] = false res end
[ "def", "filter_for", "(", "detach_with_id", ")", "unless", "@filters", ".", "key?", "detach_with_id", "if", "@return_empty_strings_for_nonexistent_filters", "return", "''", "else", "raise", "WiceGridException", ".", "new", "(", "\"No filter with Detached ID '#{detach_with_id}'!\"", ")", "end", "end", "unless", "@filters", "[", "detach_with_id", "]", "raise", "WiceGridException", ".", "new", "(", "\"Filter with Detached ID '#{detach_with_id}' has already been requested once! There cannot be two instances of the same filter on one page\"", ")", "end", "res", "=", "@filters", "[", "detach_with_id", "]", "@filters", "[", "detach_with_id", "]", "=", "false", "res", "end" ]
returns HTML code for a detached filter
[ "returns", "HTML", "code", "for", "a", "detached", "filter" ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/grid_output_buffer.rb#L27-L43
train
leikind/wice_grid
lib/wice/wice_grid_controller.rb
Wice.Controller.export_grid_if_requested
def export_grid_if_requested(opts = {}) grid = self.wice_grid_instances.detect(&:output_csv?) if grid template_name = opts[grid.name] || opts[grid.name.intern] template_name ||= grid.name + '_grid' temp_filename = render_to_string(partial: template_name) temp_filename = temp_filename.strip filename = (grid.csv_file_name || grid.name) + '.csv' grid.csv_tempfile.close send_file_rails2 temp_filename, filename: filename, type: "text/csv; charset=#{get_output_encoding grid.csv_encoding}" grid.csv_tempfile = nil true else yield if block_given? false end end
ruby
def export_grid_if_requested(opts = {}) grid = self.wice_grid_instances.detect(&:output_csv?) if grid template_name = opts[grid.name] || opts[grid.name.intern] template_name ||= grid.name + '_grid' temp_filename = render_to_string(partial: template_name) temp_filename = temp_filename.strip filename = (grid.csv_file_name || grid.name) + '.csv' grid.csv_tempfile.close send_file_rails2 temp_filename, filename: filename, type: "text/csv; charset=#{get_output_encoding grid.csv_encoding}" grid.csv_tempfile = nil true else yield if block_given? false end end
[ "def", "export_grid_if_requested", "(", "opts", "=", "{", "}", ")", "grid", "=", "self", ".", "wice_grid_instances", ".", "detect", "(", ":output_csv?", ")", "if", "grid", "template_name", "=", "opts", "[", "grid", ".", "name", "]", "||", "opts", "[", "grid", ".", "name", ".", "intern", "]", "template_name", "||=", "grid", ".", "name", "+", "'_grid'", "temp_filename", "=", "render_to_string", "(", "partial", ":", "template_name", ")", "temp_filename", "=", "temp_filename", ".", "strip", "filename", "=", "(", "grid", ".", "csv_file_name", "||", "grid", ".", "name", ")", "+", "'.csv'", "grid", ".", "csv_tempfile", ".", "close", "send_file_rails2", "temp_filename", ",", "filename", ":", "filename", ",", "type", ":", "\"text/csv; charset=#{get_output_encoding grid.csv_encoding}\"", "grid", ".", "csv_tempfile", "=", "nil", "true", "else", "yield", "if", "block_given?", "false", "end", "end" ]
+export_grid_if_requested+ is a controller method which should be called at the end of each action containing grids with enabled CSV export. CSV export will only work if each WiceGrid helper is placed in a partial of its own (requiring it from the master template of course for the usual flow). +export_grid_if_requested+ intercepts CSV export requests and evaluates the corresponding partial with the required grid helper. By default for each grid +export_grid_if_requested+ will look for a partial whose name follows the following pattern: _GRID_NAME_grid.html.erb For example, a grid named +orders+ is supposed to be found in a template called <tt>_orders_grid.html.erb</tt>, Remember that the default name of grids is +grid+. This convention can be easily overridden by supplying a hash parameter to +export_grid_if_requested+ where each key is the name of a grid, and the value is the name of the template (like it is specified for +render+, i.e. without '_' and extensions): export_grid_if_requested('grid' => 'orders', 'grid2' => 'invoices') If the request is not a CSV export request, the method does nothing and returns +false+, if it is a CSV export request, the method returns +true+. If the action has no explicit +render+ call, it's OK to just place +export_grid_if_requested+ as the last line of the action. Otherwise, to avoid double rendering, use the return value of the method to conditionally call your +render+ : export_grid_if_requested || render(action: 'index') It's also possible to supply a block which will be called if no CSV export is requested: export_grid_if_requested do render(action: 'index') end
[ "+", "export_grid_if_requested", "+", "is", "a", "controller", "method", "which", "should", "be", "called", "at", "the", "end", "of", "each", "action", "containing", "grids", "with", "enabled", "CSV", "export", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/wice_grid_controller.rb#L106-L123
train
leikind/wice_grid
lib/wice/wice_grid_controller.rb
Wice.Controller.wice_grid_custom_filter_params
def wice_grid_custom_filter_params(opts = {}) options = { grid_name: 'grid', attribute: nil, model: nil, value: nil } options.merge!(opts) [:attribute, :value].each do |key| raise ::Wice::WiceGridArgumentError.new("wice_grid_custom_filter_params: :#{key} is a mandatory argument") unless options[key] end attr_name = if options[:model] unless options[:model].nil? options[:model] = options[:model].constantize if options[:model].is_a? String raise Wice::WiceGridArgumentError.new('Option :model can be either a class or a string instance') unless options[:model].is_a? Class end options[:model].table_name + '.' + options[:attribute] else options[:attribute] end { "#{options[:grid_name]}[f][#{attr_name}][]" => options[:value] } end
ruby
def wice_grid_custom_filter_params(opts = {}) options = { grid_name: 'grid', attribute: nil, model: nil, value: nil } options.merge!(opts) [:attribute, :value].each do |key| raise ::Wice::WiceGridArgumentError.new("wice_grid_custom_filter_params: :#{key} is a mandatory argument") unless options[key] end attr_name = if options[:model] unless options[:model].nil? options[:model] = options[:model].constantize if options[:model].is_a? String raise Wice::WiceGridArgumentError.new('Option :model can be either a class or a string instance') unless options[:model].is_a? Class end options[:model].table_name + '.' + options[:attribute] else options[:attribute] end { "#{options[:grid_name]}[f][#{attr_name}][]" => options[:value] } end
[ "def", "wice_grid_custom_filter_params", "(", "opts", "=", "{", "}", ")", "options", "=", "{", "grid_name", ":", "'grid'", ",", "attribute", ":", "nil", ",", "model", ":", "nil", ",", "value", ":", "nil", "}", "options", ".", "merge!", "(", "opts", ")", "[", ":attribute", ",", ":value", "]", ".", "each", "do", "|", "key", "|", "raise", "::", "Wice", "::", "WiceGridArgumentError", ".", "new", "(", "\"wice_grid_custom_filter_params: :#{key} is a mandatory argument\"", ")", "unless", "options", "[", "key", "]", "end", "attr_name", "=", "if", "options", "[", ":model", "]", "unless", "options", "[", ":model", "]", ".", "nil?", "options", "[", ":model", "]", "=", "options", "[", ":model", "]", ".", "constantize", "if", "options", "[", ":model", "]", ".", "is_a?", "String", "raise", "Wice", "::", "WiceGridArgumentError", ".", "new", "(", "'Option :model can be either a class or a string instance'", ")", "unless", "options", "[", ":model", "]", ".", "is_a?", "Class", "end", "options", "[", ":model", "]", ".", "table_name", "+", "'.'", "+", "options", "[", ":attribute", "]", "else", "options", "[", ":attribute", "]", "end", "{", "\"#{options[:grid_name]}[f][#{attr_name}][]\"", "=>", "options", "[", ":value", "]", "}", "end" ]
+wice_grid_custom_filter_params+ generates HTTP parameters understood by WiceGrid custom filters. Combined with Rails route helpers it allows to generate links leading to grids with pre-selected custom filters. Parameters: * <tt>:grid_name</tt> - The name of the grid. Just like parameter <tt>:name</tt> of <tt>initialize_grid</tt>, the parameter is optional, and when absent, the name <tt>'grid'</tt> is assumed * <tt>:attribute</tt> and <tt>:model</tt> - should be the same as <tt>:attribute</tt> and <tt>:model</tt> of the column declaration with the target custom filter. * <tt>:value</tt> - the value of the column filter.
[ "+", "wice_grid_custom_filter_params", "+", "generates", "HTTP", "parameters", "understood", "by", "WiceGrid", "custom", "filters", ".", "Combined", "with", "Rails", "route", "helpers", "it", "allows", "to", "generate", "links", "leading", "to", "grids", "with", "pre", "-", "selected", "custom", "filters", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/wice_grid_controller.rb#L136-L160
train
leikind/wice_grid
lib/wice/helpers/wice_grid_misc_view_helpers.rb
Wice.GridViewHelper.dump_filter_parameters_as_hidden_fields
def dump_filter_parameters_as_hidden_fields(grid) unless grid.is_a? WiceGrid raise WiceGridArgumentError.new('dump_filter_parameters_as_hidden_fields: the parameter must be a WiceGrid instance.') end grid.get_state_as_parameter_value_pairs(true).collect do|param_name, value| hidden_field_tag(param_name, value, id: "hidden-#{param_name.gsub(/[\[\]]/, '-')}") end.join("\n").html_safe end
ruby
def dump_filter_parameters_as_hidden_fields(grid) unless grid.is_a? WiceGrid raise WiceGridArgumentError.new('dump_filter_parameters_as_hidden_fields: the parameter must be a WiceGrid instance.') end grid.get_state_as_parameter_value_pairs(true).collect do|param_name, value| hidden_field_tag(param_name, value, id: "hidden-#{param_name.gsub(/[\[\]]/, '-')}") end.join("\n").html_safe end
[ "def", "dump_filter_parameters_as_hidden_fields", "(", "grid", ")", "unless", "grid", ".", "is_a?", "WiceGrid", "raise", "WiceGridArgumentError", ".", "new", "(", "'dump_filter_parameters_as_hidden_fields: the parameter must be a WiceGrid instance.'", ")", "end", "grid", ".", "get_state_as_parameter_value_pairs", "(", "true", ")", ".", "collect", "do", "|", "param_name", ",", "value", "|", "hidden_field_tag", "(", "param_name", ",", "value", ",", "id", ":", "\"hidden-#{param_name.gsub(/[\\[\\]]/, '-')}\"", ")", "end", ".", "join", "(", "\"\\n\"", ")", ".", "html_safe", "end" ]
This method dumps all HTTP parameters related to filtering and ordering of a certain grid as hidden form fields. This might be required if you want to keep the state of a grid while reloading the page using other forms. The only parameter is a grid object returned by +initialize_grid+ in the controller.
[ "This", "method", "dumps", "all", "HTTP", "parameters", "related", "to", "filtering", "and", "ordering", "of", "a", "certain", "grid", "as", "hidden", "form", "fields", ".", "This", "might", "be", "required", "if", "you", "want", "to", "keep", "the", "state", "of", "a", "grid", "while", "reloading", "the", "page", "using", "other", "forms", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/helpers/wice_grid_misc_view_helpers.rb#L9-L17
train
leikind/wice_grid
lib/wice/helpers/wice_grid_misc_view_helpers.rb
Wice.GridViewHelper.filter_and_order_state_as_hash
def filter_and_order_state_as_hash(grid) { grid.name => { 'f' => grid.status[:f], 'order' => grid.status[:order], 'order_direction' => grid.status[:order_direction] } } end
ruby
def filter_and_order_state_as_hash(grid) { grid.name => { 'f' => grid.status[:f], 'order' => grid.status[:order], 'order_direction' => grid.status[:order_direction] } } end
[ "def", "filter_and_order_state_as_hash", "(", "grid", ")", "{", "grid", ".", "name", "=>", "{", "'f'", "=>", "grid", ".", "status", "[", ":f", "]", ",", "'order'", "=>", "grid", ".", "status", "[", ":order", "]", ",", "'order_direction'", "=>", "grid", ".", "status", "[", ":order_direction", "]", "}", "}", "end" ]
This method dumps all HTTP parameters related to filtering and ordering of a certain grid in the form of a hash. This might be required if you want to keep the state of a grid while reloading the page using Rails routing helpers. The only parameter is a grid object returned by +initialize_grid+ in the controller.
[ "This", "method", "dumps", "all", "HTTP", "parameters", "related", "to", "filtering", "and", "ordering", "of", "a", "certain", "grid", "in", "the", "form", "of", "a", "hash", ".", "This", "might", "be", "required", "if", "you", "want", "to", "keep", "the", "state", "of", "a", "grid", "while", "reloading", "the", "page", "using", "Rails", "routing", "helpers", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/helpers/wice_grid_misc_view_helpers.rb#L33-L41
train
leikind/wice_grid
lib/wice/helpers/wice_grid_misc_view_helpers.rb
Wice.GridViewHelper.scaffolded_grid
def scaffolded_grid(grid_obj, opts = {}) #:nodoc: unless grid_obj.is_a? WiceGrid raise WiceGridArgumentError.new('scaffolded_grid: the parameter must be a WiceGrid instance.') end # debug grid.klass.column_names columns = grid_obj.klass.column_names if opts[:reject_attributes].is_a? Proc columns = columns.reject { |c| opts[:reject_attributes].call(c) } opts.delete(:reject_attributes) else columns = columns.reject { |c| c =~ opts[:reject_attributes] } opts.delete(:reject_attributes) end grid(grid_obj, opts) do |g| columns.each do |column_name| g.column name: column_name.humanize, attribute: column_name do |ar| ar.send(column_name) end end end end
ruby
def scaffolded_grid(grid_obj, opts = {}) #:nodoc: unless grid_obj.is_a? WiceGrid raise WiceGridArgumentError.new('scaffolded_grid: the parameter must be a WiceGrid instance.') end # debug grid.klass.column_names columns = grid_obj.klass.column_names if opts[:reject_attributes].is_a? Proc columns = columns.reject { |c| opts[:reject_attributes].call(c) } opts.delete(:reject_attributes) else columns = columns.reject { |c| c =~ opts[:reject_attributes] } opts.delete(:reject_attributes) end grid(grid_obj, opts) do |g| columns.each do |column_name| g.column name: column_name.humanize, attribute: column_name do |ar| ar.send(column_name) end end end end
[ "def", "scaffolded_grid", "(", "grid_obj", ",", "opts", "=", "{", "}", ")", "#:nodoc:", "unless", "grid_obj", ".", "is_a?", "WiceGrid", "raise", "WiceGridArgumentError", ".", "new", "(", "'scaffolded_grid: the parameter must be a WiceGrid instance.'", ")", "end", "# debug grid.klass.column_names", "columns", "=", "grid_obj", ".", "klass", ".", "column_names", "if", "opts", "[", ":reject_attributes", "]", ".", "is_a?", "Proc", "columns", "=", "columns", ".", "reject", "{", "|", "c", "|", "opts", "[", ":reject_attributes", "]", ".", "call", "(", "c", ")", "}", "opts", ".", "delete", "(", ":reject_attributes", ")", "else", "columns", "=", "columns", ".", "reject", "{", "|", "c", "|", "c", "=~", "opts", "[", ":reject_attributes", "]", "}", "opts", ".", "delete", "(", ":reject_attributes", ")", "end", "grid", "(", "grid_obj", ",", "opts", ")", "do", "|", "g", "|", "columns", ".", "each", "do", "|", "column_name", "|", "g", ".", "column", "name", ":", "column_name", ".", "humanize", ",", "attribute", ":", "column_name", "do", "|", "ar", "|", "ar", ".", "send", "(", "column_name", ")", "end", "end", "end", "end" ]
secret but stupid weapon - takes an ActiveRecord and using reflection tries to build all the column clauses by itself. WiceGrid is not a scaffolding solution, I hate scaffolding and how certain idiots associate scaffolding with Rails, so I do not document this method to avoid contributing to this misunderstanding.
[ "secret", "but", "stupid", "weapon", "-", "takes", "an", "ActiveRecord", "and", "using", "reflection", "tries", "to", "build", "all", "the", "column", "clauses", "by", "itself", ".", "WiceGrid", "is", "not", "a", "scaffolding", "solution", "I", "hate", "scaffolding", "and", "how", "certain", "idiots", "associate", "scaffolding", "with", "Rails", "so", "I", "do", "not", "document", "this", "method", "to", "avoid", "contributing", "to", "this", "misunderstanding", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/helpers/wice_grid_misc_view_helpers.rb#L51-L72
train
leikind/wice_grid
lib/wice/grid_renderer.rb
Wice.GridRenderer.action_column
def action_column(opts = {}, &block) if @action_column_present raise Wice::WiceGridException.new('There can be only one action column in a WiceGrid') end options = { param_name: :selected, html: {}, select_all_buttons: true, object_property: :id, html_check_box: true } opts.assert_valid_keys(options.keys) options.merge!(opts) @action_column_present = true column_processor_klass = Columns.get_view_column_processor(:action) @columns << column_processor_klass.new( @grid, options[:html], options[:param_name], options[:select_all_buttons], options[:object_property], options[:html_check_box], @view, block ) end
ruby
def action_column(opts = {}, &block) if @action_column_present raise Wice::WiceGridException.new('There can be only one action column in a WiceGrid') end options = { param_name: :selected, html: {}, select_all_buttons: true, object_property: :id, html_check_box: true } opts.assert_valid_keys(options.keys) options.merge!(opts) @action_column_present = true column_processor_klass = Columns.get_view_column_processor(:action) @columns << column_processor_klass.new( @grid, options[:html], options[:param_name], options[:select_all_buttons], options[:object_property], options[:html_check_box], @view, block ) end
[ "def", "action_column", "(", "opts", "=", "{", "}", ",", "&", "block", ")", "if", "@action_column_present", "raise", "Wice", "::", "WiceGridException", ".", "new", "(", "'There can be only one action column in a WiceGrid'", ")", "end", "options", "=", "{", "param_name", ":", ":selected", ",", "html", ":", "{", "}", ",", "select_all_buttons", ":", "true", ",", "object_property", ":", ":id", ",", "html_check_box", ":", "true", "}", "opts", ".", "assert_valid_keys", "(", "options", ".", "keys", ")", "options", ".", "merge!", "(", "opts", ")", "@action_column_present", "=", "true", "column_processor_klass", "=", "Columns", ".", "get_view_column_processor", "(", ":action", ")", "@columns", "<<", "column_processor_klass", ".", "new", "(", "@grid", ",", "options", "[", ":html", "]", ",", "options", "[", ":param_name", "]", ",", "options", "[", ":select_all_buttons", "]", ",", "options", "[", ":object_property", "]", ",", "options", "[", ":html_check_box", "]", ",", "@view", ",", "block", ")", "end" ]
Adds a column with checkboxes for each record. Useful for actions with multiple records, for example, deleting selected records. Please note that +action_column+ only creates the checkboxes and the 'Select All' and 'Deselect All' buttons, and the form itelf as well as processing the parameters should be taken care of by the application code. * <tt>:param_name</tt> - The name of the HTTP parameter. The complete HTTP parameter is <tt>"#{grid_name}[#{param_name}][]"</tt>. The default param_name is 'selected'. * <tt>:html</tt> - a hash of HTML attributes to be included into the <tt>td</tt> tag. * <tt>:select_all_buttons</tt> - show/hide buttons 'Select All' and 'Deselect All' in the column header. The default is +true+. * <tt>:object_property</tt> - a method used to obtain the value for the HTTP parameter. The default is +id+. * <tt>:html_check_box</tt> - can be used to switch from a real check box to two images. The default is +true+. You can hide a certain action checkbox if you add the usual block to +g.action_column+, just like with the +g.column+ definition. If the block returns +nil+ or +false+ no checkbox will be rendered.
[ "Adds", "a", "column", "with", "checkboxes", "for", "each", "record", ".", "Useful", "for", "actions", "with", "multiple", "records", "for", "example", "deleting", "selected", "records", ".", "Please", "note", "that", "+", "action_column", "+", "only", "creates", "the", "checkboxes", "and", "the", "Select", "All", "and", "Deselect", "All", "buttons", "and", "the", "form", "itelf", "as", "well", "as", "processing", "the", "parameters", "should", "be", "taken", "care", "of", "by", "the", "application", "code", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/grid_renderer.rb#L158-L186
train
leikind/wice_grid
lib/wice_grid.rb
Wice.WiceGrid.distinct_values_for_column
def distinct_values_for_column(column) #:nodoc: column.model.select("distinct #{column.name}").order("#{column.name} asc").collect do|ar| ar[column.name] end.reject(&:blank?).map { |i| [i, i] } end
ruby
def distinct_values_for_column(column) #:nodoc: column.model.select("distinct #{column.name}").order("#{column.name} asc").collect do|ar| ar[column.name] end.reject(&:blank?).map { |i| [i, i] } end
[ "def", "distinct_values_for_column", "(", "column", ")", "#:nodoc:", "column", ".", "model", ".", "select", "(", "\"distinct #{column.name}\"", ")", ".", "order", "(", "\"#{column.name} asc\"", ")", ".", "collect", "do", "|", "ar", "|", "ar", "[", "column", ".", "name", "]", "end", ".", "reject", "(", ":blank?", ")", ".", "map", "{", "|", "i", "|", "[", "i", ",", "i", "]", "}", "end" ]
with this variant we get even those values which do not appear in the resultset
[ "with", "this", "variant", "we", "get", "even", "those", "values", "which", "do", "not", "appear", "in", "the", "resultset" ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice_grid.rb#L466-L470
train
leikind/wice_grid
lib/wice/helpers/wice_grid_view_helpers.rb
Wice.GridViewHelper.grid
def grid(grid, opts = {}, &block) raise WiceGridArgumentError.new('Missing block for the grid helper.' \ ' For detached filters use first define_grid with the same API as grid, ' \ 'then grid_filter to add filters, and then render_grid to actually show the grid') if block.nil? define_grid(grid, opts, &block) render_grid(grid) end
ruby
def grid(grid, opts = {}, &block) raise WiceGridArgumentError.new('Missing block for the grid helper.' \ ' For detached filters use first define_grid with the same API as grid, ' \ 'then grid_filter to add filters, and then render_grid to actually show the grid') if block.nil? define_grid(grid, opts, &block) render_grid(grid) end
[ "def", "grid", "(", "grid", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "raise", "WiceGridArgumentError", ".", "new", "(", "'Missing block for the grid helper.'", "' For detached filters use first define_grid with the same API as grid, '", "'then grid_filter to add filters, and then render_grid to actually show the grid'", ")", "if", "block", ".", "nil?", "define_grid", "(", "grid", ",", "opts", ",", "block", ")", "render_grid", "(", "grid", ")", "end" ]
View helper for rendering the grid. The first parameter is a grid object returned by +initialize_grid+ in the controller. The second parameter is a hash of options: * <tt>:html</tt> - a hash of HTML attributes to be included into the <tt>table</tt> tag. * <tt>:class</tt> - a shortcut for <tt>html: {class: 'css_class'}</tt> * <tt>:header_tr_html</tt> - a hash of HTML attributes to be included into the first <tt>tr</tt> tag (or two first <tt>tr</tt>'s if the filter row is present). * <tt>:show_filters</tt> - defines when the filter is shown. Possible values are: * <tt>:when_filtered</tt> - the filter is shown when the current table is the result of filtering * <tt>:always</tt> or <tt>true</tt> - show the filter always * <tt>:no</tt> or <tt>false</tt> - never show the filter * <tt>:upper_pagination_panel</tt> - a boolean value which defines whether there is an additional pagination panel on top of the table. By default it is false. * <tt>:extra_request_parameters</tt> - a hash which will be added as additional HTTP request parameters to all links generated by the grid, be it sorting links, filters, or the 'Reset Filter' icon. Please note that WiceGrid respects and retains all request parameters already present in the URL which formed the page, so there is no need to enumerate them in <tt>:extra_request_parameters</tt>. A typical usage of <tt>:extra_request_parameters</tt> is a page with javascript tabs - changing the active tab does not reload the page, but if one such tab contains a WiceGrid, it could be required that if the user orders or filters the grid, the result page should have the tab with the grid activated. For this we need to send an additional parameter specifying from which tab the request was generated. * <tt>:sorting_dependant_row_cycling</tt> - When set to true (by default it is false) the row styles +odd+ and +even+ will be changed only when the content of the cell belonging to the sorted column changes. In other words, rows with identical values in the ordered column will have the same style (color). * <tt>:allow_showing_all_records</tt> - allow or prohibit the "All Records" mode. * <tt>:hide_reset_button</tt> - Do not show the default Filter Reset button. Useful when using a custom reset button. By default it is false. * <tt>:hide_submit_button</tt> - Do not show the default Filter Submit button. Useful when using a custom submit button By default it is false. * <tt>:hide_csv_button</tt> - a boolean value which defines whether the default Export To CSV button should be rendered. Useful when using a custom Export To CSV button. By default it is false. Please read README for more insights. The block contains definitions of grid columns using the +column+ method sent to the object yielded into the block. In other words, the value returned by each of the blocks defines the content of a cell, the first block is called for cells of the first column for each row (each ActiveRecord instance), the second block is called for cells of the second column, and so on. See the example: <%= grid(@accounts_grid, html: {class: 'grid_style', id: 'accounts_grid'}, header_tr_html: {class: 'grid_headers'}) do |g| g.column name: 'Username', attribute: 'username' do |account| account.username end g.column name: 'application_account.field.identity_id'._, attribute: 'firstname', model: Person do |account| link_to(account.identity.name, identity_path(account.identity)) end g.column do |account| link_to('Edit', edit_account_path(account)) end end -%> Defaults for parameters <tt>:show_filters</tt> and <tt>:upper_pagination_panel</tt> can be changed in <tt>lib/wice_grid_config.rb</tt> using constants <tt>Wice::Defaults::SHOW_FILTER</tt> and <tt>WiceGrid::Defaults::SHOW_UPPER_PAGINATION_PANEL</tt>, this is convenient if you want to set a project wide setting without having to repeat it for every grid instance. Pease read documentation about the +column+ method to achieve the enlightenment.
[ "View", "helper", "for", "rendering", "the", "grid", "." ]
a8080a7ddeda45c7719132fc634ad3313f77e730
https://github.com/leikind/wice_grid/blob/a8080a7ddeda45c7719132fc634ad3313f77e730/lib/wice/helpers/wice_grid_view_helpers.rb#L70-L76
train
Sology/smart_listing
app/helpers/smart_listing/helper.rb
SmartListing.Helper.smart_listing_for
def smart_listing_for name, *args, &block raise ArgumentError, "Missing block" unless block_given? name = name.to_sym options = args.extract_options! bare = options.delete(:bare) builder = Builder.new(name, @smart_listings[name], self, options, block) output = "" data = {} data[smart_listing_config.data_attributes(:max_count)] = @smart_listings[name].max_count if @smart_listings[name].max_count && @smart_listings[name].max_count > 0 data[smart_listing_config.data_attributes(:item_count)] = @smart_listings[name].count data[smart_listing_config.data_attributes(:href)] = @smart_listings[name].href if @smart_listings[name].href data[smart_listing_config.data_attributes(:callback_href)] = @smart_listings[name].callback_href if @smart_listings[name].callback_href data.merge!(options[:data]) if options[:data] if bare output = capture(builder, &block) else output = content_tag(:div, :class => smart_listing_config.classes(:main), :id => name, :data => data) do concat(content_tag(:div, "", :class => smart_listing_config.classes(:loading))) concat(content_tag(:div, :class => smart_listing_config.classes(:content)) do concat(capture(builder, &block)) end) end end output end
ruby
def smart_listing_for name, *args, &block raise ArgumentError, "Missing block" unless block_given? name = name.to_sym options = args.extract_options! bare = options.delete(:bare) builder = Builder.new(name, @smart_listings[name], self, options, block) output = "" data = {} data[smart_listing_config.data_attributes(:max_count)] = @smart_listings[name].max_count if @smart_listings[name].max_count && @smart_listings[name].max_count > 0 data[smart_listing_config.data_attributes(:item_count)] = @smart_listings[name].count data[smart_listing_config.data_attributes(:href)] = @smart_listings[name].href if @smart_listings[name].href data[smart_listing_config.data_attributes(:callback_href)] = @smart_listings[name].callback_href if @smart_listings[name].callback_href data.merge!(options[:data]) if options[:data] if bare output = capture(builder, &block) else output = content_tag(:div, :class => smart_listing_config.classes(:main), :id => name, :data => data) do concat(content_tag(:div, "", :class => smart_listing_config.classes(:loading))) concat(content_tag(:div, :class => smart_listing_config.classes(:content)) do concat(capture(builder, &block)) end) end end output end
[ "def", "smart_listing_for", "name", ",", "*", "args", ",", "&", "block", "raise", "ArgumentError", ",", "\"Missing block\"", "unless", "block_given?", "name", "=", "name", ".", "to_sym", "options", "=", "args", ".", "extract_options!", "bare", "=", "options", ".", "delete", "(", ":bare", ")", "builder", "=", "Builder", ".", "new", "(", "name", ",", "@smart_listings", "[", "name", "]", ",", "self", ",", "options", ",", "block", ")", "output", "=", "\"\"", "data", "=", "{", "}", "data", "[", "smart_listing_config", ".", "data_attributes", "(", ":max_count", ")", "]", "=", "@smart_listings", "[", "name", "]", ".", "max_count", "if", "@smart_listings", "[", "name", "]", ".", "max_count", "&&", "@smart_listings", "[", "name", "]", ".", "max_count", ">", "0", "data", "[", "smart_listing_config", ".", "data_attributes", "(", ":item_count", ")", "]", "=", "@smart_listings", "[", "name", "]", ".", "count", "data", "[", "smart_listing_config", ".", "data_attributes", "(", ":href", ")", "]", "=", "@smart_listings", "[", "name", "]", ".", "href", "if", "@smart_listings", "[", "name", "]", ".", "href", "data", "[", "smart_listing_config", ".", "data_attributes", "(", ":callback_href", ")", "]", "=", "@smart_listings", "[", "name", "]", ".", "callback_href", "if", "@smart_listings", "[", "name", "]", ".", "callback_href", "data", ".", "merge!", "(", "options", "[", ":data", "]", ")", "if", "options", "[", ":data", "]", "if", "bare", "output", "=", "capture", "(", "builder", ",", "block", ")", "else", "output", "=", "content_tag", "(", ":div", ",", ":class", "=>", "smart_listing_config", ".", "classes", "(", ":main", ")", ",", ":id", "=>", "name", ",", ":data", "=>", "data", ")", "do", "concat", "(", "content_tag", "(", ":div", ",", "\"\"", ",", ":class", "=>", "smart_listing_config", ".", "classes", "(", ":loading", ")", ")", ")", "concat", "(", "content_tag", "(", ":div", ",", ":class", "=>", "smart_listing_config", ".", "classes", "(", ":content", ")", ")", "do", "concat", "(", "capture", "(", "builder", ",", "block", ")", ")", "end", ")", "end", "end", "output", "end" ]
Outputs smart list container
[ "Outputs", "smart", "list", "container" ]
064ba282d0bb6cab9dd03b7fc57c341755903358
https://github.com/Sology/smart_listing/blob/064ba282d0bb6cab9dd03b7fc57c341755903358/app/helpers/smart_listing/helper.rb#L196-L225
train