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
github/janky
lib/janky/branch.rb
Janky.Branch.to_hash
def to_hash { :name => repository.name, :status => status, :sha1 => (current_build && current_build.sha1), :compare => (current_build && current_build.compare) } end
ruby
def to_hash { :name => repository.name, :status => status, :sha1 => (current_build && current_build.sha1), :compare => (current_build && current_build.compare) } end
[ "def", "to_hash", "{", ":name", "=>", "repository", ".", "name", ",", ":status", "=>", "status", ",", ":sha1", "=>", "(", "current_build", "&&", "current_build", ".", "sha1", ")", ",", ":compare", "=>", "(", "current_build", "&&", "current_build", ".", "compare", ")", "}", "end" ]
Hash representation of this branch status. Returns a Hash with the name, status, sha1 and compare url.
[ "Hash", "representation", "of", "this", "branch", "status", "." ]
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/branch.rb#L130-L137
train
github/janky
lib/janky/repository.rb
Janky.Repository.job_name
def job_name md5 = Digest::MD5.new md5 << name md5 << uri md5 << job_config_path.read md5 << builder.callback_url.to_s "#{name}-#{md5.hexdigest[0,12]}" end
ruby
def job_name md5 = Digest::MD5.new md5 << name md5 << uri md5 << job_config_path.read md5 << builder.callback_url.to_s "#{name}-#{md5.hexdigest[0,12]}" end
[ "def", "job_name", "md5", "=", "Digest", "::", "MD5", ".", "new", "md5", "<<", "name", "md5", "<<", "uri", "md5", "<<", "job_config_path", ".", "read", "md5", "<<", "builder", ".", "callback_url", ".", "to_s", "\"#{name}-#{md5.hexdigest[0,12]}\"", "end" ]
Calculate the name of the Jenkins job. Returns a String hash of this Repository name and uri.
[ "Calculate", "the", "name", "of", "the", "Jenkins", "job", "." ]
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/repository.rb#L234-L241
train
github/janky
lib/janky/build.rb
Janky.Build.rerun
def rerun(new_room_id = nil) build = branch.build_for(commit, new_room_id) build.run build end
ruby
def rerun(new_room_id = nil) build = branch.build_for(commit, new_room_id) build.run build end
[ "def", "rerun", "(", "new_room_id", "=", "nil", ")", "build", "=", "branch", ".", "build_for", "(", "commit", ",", "new_room_id", ")", "build", ".", "run", "build", "end" ]
Run a copy of itself. Typically used to force a build in case of temporary test failure or when auto-build is disabled. new_room_id - optional Campfire room String ID. Defaults to the room of the build being re-run. Returns the build copy.
[ "Run", "a", "copy", "of", "itself", ".", "Typically", "used", "to", "force", "a", "build", "in", "case", "of", "temporary", "test", "failure", "or", "when", "auto", "-", "build", "is", "disabled", "." ]
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/build.rb#L138-L142
train
github/janky
lib/janky/build.rb
Janky.Build.start
def start(url, now) if started? raise Error, "Build #{id} already started" elsif completed? raise Error, "Build #{id} already completed" else update_attributes!(:url => url, :started_at => now) Notifier.started(self) end end
ruby
def start(url, now) if started? raise Error, "Build #{id} already started" elsif completed? raise Error, "Build #{id} already completed" else update_attributes!(:url => url, :started_at => now) Notifier.started(self) end end
[ "def", "start", "(", "url", ",", "now", ")", "if", "started?", "raise", "Error", ",", "\"Build #{id} already started\"", "elsif", "completed?", "raise", "Error", ",", "\"Build #{id} already completed\"", "else", "update_attributes!", "(", ":url", "=>", "url", ",", ":started_at", "=>", "now", ")", "Notifier", ".", "started", "(", "self", ")", "end", "end" ]
Mark the build as started. url - the full String URL of the build on the Jenkins server. now - the Time at which the build started. Returns nothing or raise an Error for weird transitions.
[ "Mark", "the", "build", "as", "started", "." ]
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/build.rb#L172-L181
train
github/janky
lib/janky/build.rb
Janky.Build.complete
def complete(green, now) if ! started? raise Error, "Build #{id} not started" elsif completed? raise Error, "Build #{id} already completed" else update_attributes!( :green => green, :completed_at => now, :output => output_remote ) Notifier.completed(self) end end
ruby
def complete(green, now) if ! started? raise Error, "Build #{id} not started" elsif completed? raise Error, "Build #{id} already completed" else update_attributes!( :green => green, :completed_at => now, :output => output_remote ) Notifier.completed(self) end end
[ "def", "complete", "(", "green", ",", "now", ")", "if", "!", "started?", "raise", "Error", ",", "\"Build #{id} not started\"", "elsif", "completed?", "raise", "Error", ",", "\"Build #{id} already completed\"", "else", "update_attributes!", "(", ":green", "=>", "green", ",", ":completed_at", "=>", "now", ",", ":output", "=>", "output_remote", ")", "Notifier", ".", "completed", "(", "self", ")", "end", "end" ]
Mark the build as complete, store the build output and notify Campfire. green - Boolean indicating build success. now - the Time at which the build completed. Returns nothing or raise an Error for weird transitions.
[ "Mark", "the", "build", "as", "complete", "store", "the", "build", "output", "and", "notify", "Campfire", "." ]
59c17b0b9beb8e126bcf2a2e641203fbca7ded06
https://github.com/github/janky/blob/59c17b0b9beb8e126bcf2a2e641203fbca7ded06/lib/janky/build.rb#L189-L202
train
discourse/logster
lib/logster/message.rb
Logster.Message.solved_keys
def solved_keys if Array === env versions = env.map { |single_env| single_env["application_version"] } else versions = env["application_version"] end if versions && backtrace && backtrace.length > 0 versions = [versions] if String === versions versions.map do |version| Digest::SHA1.hexdigest "#{version} #{backtrace}" end end end
ruby
def solved_keys if Array === env versions = env.map { |single_env| single_env["application_version"] } else versions = env["application_version"] end if versions && backtrace && backtrace.length > 0 versions = [versions] if String === versions versions.map do |version| Digest::SHA1.hexdigest "#{version} #{backtrace}" end end end
[ "def", "solved_keys", "if", "Array", "===", "env", "versions", "=", "env", ".", "map", "{", "|", "single_env", "|", "single_env", "[", "\"application_version\"", "]", "}", "else", "versions", "=", "env", "[", "\"application_version\"", "]", "end", "if", "versions", "&&", "backtrace", "&&", "backtrace", ".", "length", ">", "0", "versions", "=", "[", "versions", "]", "if", "String", "===", "versions", "versions", ".", "map", "do", "|", "version", "|", "Digest", "::", "SHA1", ".", "hexdigest", "\"#{version} #{backtrace}\"", "end", "end", "end" ]
todo - memoize?
[ "todo", "-", "memoize?" ]
5cdcb76bccf7d79f7b864f11fd4f586fa685b7fc
https://github.com/discourse/logster/blob/5cdcb76bccf7d79f7b864f11fd4f586fa685b7fc/lib/logster/message.rb#L112-L126
train
bogdan/datagrid
lib/datagrid/helper.rb
Datagrid.Helper.datagrid_rows
def datagrid_rows(grid, assets = grid.assets, **options, &block) datagrid_renderer.rows(grid, assets, options, &block) end
ruby
def datagrid_rows(grid, assets = grid.assets, **options, &block) datagrid_renderer.rows(grid, assets, options, &block) end
[ "def", "datagrid_rows", "(", "grid", ",", "assets", "=", "grid", ".", "assets", ",", "**", "options", ",", "&", "block", ")", "datagrid_renderer", ".", "rows", "(", "grid", ",", "assets", ",", "options", ",", "block", ")", "end" ]
Renders HTML table rows using given grid definition using columns defined in it. Allows to provide a custom layout for each for in place with a block Supported options: * <tt>:columns</tt> - Array of column names to display. Used in case when same grid class is used in different places and needs different columns. Default: all defined columns. * <tt>:partials</tt> - Path for partials lookup. Default: 'datagrid'. = datagrid_rows(grid) # Generic table rows Layout = datagrid_rows(grid) do |row| # Custom Layout %tr %td= row.project_name %td.project-status{class: row.status}= row.status
[ "Renders", "HTML", "table", "rows", "using", "given", "grid", "definition", "using", "columns", "defined", "in", "it", ".", "Allows", "to", "provide", "a", "custom", "layout", "for", "each", "for", "in", "place", "with", "a", "block" ]
bd54295b5e7476a86113c317a6c980a8cd5a2f82
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/helper.rb#L75-L77
train
bogdan/datagrid
lib/datagrid/helper.rb
Datagrid.Helper.datagrid_row
def datagrid_row(grid, asset, &block) HtmlRow.new(self, grid, asset).tap do |row| if block_given? return capture(row, &block) end end end
ruby
def datagrid_row(grid, asset, &block) HtmlRow.new(self, grid, asset).tap do |row| if block_given? return capture(row, &block) end end end
[ "def", "datagrid_row", "(", "grid", ",", "asset", ",", "&", "block", ")", "HtmlRow", ".", "new", "(", "self", ",", "grid", ",", "asset", ")", ".", "tap", "do", "|", "row", "|", "if", "block_given?", "return", "capture", "(", "row", ",", "block", ")", "end", "end", "end" ]
Provides access to datagrid columns data. # Suppose that <tt>grid</tt> has first_name and last_name columns <%= datagrid_row(grid, user) do |row| %> <tr> <td><%= row.first_name %></td> <td><%= row.last_name %></td> </tr> <% end %> Used in case you want to build html table completelly manually
[ "Provides", "access", "to", "datagrid", "columns", "data", "." ]
bd54295b5e7476a86113c317a6c980a8cd5a2f82
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/helper.rb#L111-L117
train
bogdan/datagrid
lib/datagrid/helper.rb
Datagrid.Helper.datagrid_order_path
def datagrid_order_path(grid, column, descending) datagrid_renderer.order_path(grid, column, descending, request) end
ruby
def datagrid_order_path(grid, column, descending) datagrid_renderer.order_path(grid, column, descending, request) end
[ "def", "datagrid_order_path", "(", "grid", ",", "column", ",", "descending", ")", "datagrid_renderer", ".", "order_path", "(", "grid", ",", "column", ",", "descending", ",", "request", ")", "end" ]
Generates an ascending or descending order url for the given column
[ "Generates", "an", "ascending", "or", "descending", "order", "url", "for", "the", "given", "column" ]
bd54295b5e7476a86113c317a6c980a8cd5a2f82
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/helper.rb#L120-L122
train
bogdan/datagrid
lib/datagrid/form_builder.rb
Datagrid.FormBuilder.datagrid_filter
def datagrid_filter(filter_or_attribute, options = {}, &block) filter = datagrid_get_filter(filter_or_attribute) options = add_html_classes(options, filter.name, datagrid_filter_html_class(filter)) # Prevent partials option from appearing in HTML attributes options.delete(:partials) # Legacy option self.send(filter.form_builder_helper_name, filter, options, &block) end
ruby
def datagrid_filter(filter_or_attribute, options = {}, &block) filter = datagrid_get_filter(filter_or_attribute) options = add_html_classes(options, filter.name, datagrid_filter_html_class(filter)) # Prevent partials option from appearing in HTML attributes options.delete(:partials) # Legacy option self.send(filter.form_builder_helper_name, filter, options, &block) end
[ "def", "datagrid_filter", "(", "filter_or_attribute", ",", "options", "=", "{", "}", ",", "&", "block", ")", "filter", "=", "datagrid_get_filter", "(", "filter_or_attribute", ")", "options", "=", "add_html_classes", "(", "options", ",", "filter", ".", "name", ",", "datagrid_filter_html_class", "(", "filter", ")", ")", "# Prevent partials option from appearing in HTML attributes", "options", ".", "delete", "(", ":partials", ")", "# Legacy option", "self", ".", "send", "(", "filter", ".", "form_builder_helper_name", ",", "filter", ",", "options", ",", "block", ")", "end" ]
Returns a form input html for the corresponding filter name
[ "Returns", "a", "form", "input", "html", "for", "the", "corresponding", "filter", "name" ]
bd54295b5e7476a86113c317a6c980a8cd5a2f82
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/form_builder.rb#L7-L13
train
bogdan/datagrid
lib/datagrid/form_builder.rb
Datagrid.FormBuilder.datagrid_label
def datagrid_label(filter_or_attribute, options_or_text = {}, options = {}, &block) filter = datagrid_get_filter(filter_or_attribute) text, options = options_or_text.is_a?(Hash) ? [filter.header, options_or_text] : [options_or_text, options] label(filter.name, text, options, &block) end
ruby
def datagrid_label(filter_or_attribute, options_or_text = {}, options = {}, &block) filter = datagrid_get_filter(filter_or_attribute) text, options = options_or_text.is_a?(Hash) ? [filter.header, options_or_text] : [options_or_text, options] label(filter.name, text, options, &block) end
[ "def", "datagrid_label", "(", "filter_or_attribute", ",", "options_or_text", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "filter", "=", "datagrid_get_filter", "(", "filter_or_attribute", ")", "text", ",", "options", "=", "options_or_text", ".", "is_a?", "(", "Hash", ")", "?", "[", "filter", ".", "header", ",", "options_or_text", "]", ":", "[", "options_or_text", ",", "options", "]", "label", "(", "filter", ".", "name", ",", "text", ",", "options", ",", "block", ")", "end" ]
Returns a form label html for the corresponding filter name
[ "Returns", "a", "form", "label", "html", "for", "the", "corresponding", "filter", "name" ]
bd54295b5e7476a86113c317a6c980a8cd5a2f82
https://github.com/bogdan/datagrid/blob/bd54295b5e7476a86113c317a6c980a8cd5a2f82/lib/datagrid/form_builder.rb#L16-L20
train
rzane/baby_squeel
lib/baby_squeel/dsl.rb
BabySqueel.DSL._
def _(expr) expr = Arel.sql(expr.to_sql) if expr.is_a? ::ActiveRecord::Relation Nodes.wrap Arel::Nodes::Grouping.new(expr) end
ruby
def _(expr) expr = Arel.sql(expr.to_sql) if expr.is_a? ::ActiveRecord::Relation Nodes.wrap Arel::Nodes::Grouping.new(expr) end
[ "def", "_", "(", "expr", ")", "expr", "=", "Arel", ".", "sql", "(", "expr", ".", "to_sql", ")", "if", "expr", ".", "is_a?", "::", "ActiveRecord", "::", "Relation", "Nodes", ".", "wrap", "Arel", "::", "Nodes", "::", "Grouping", ".", "new", "(", "expr", ")", "end" ]
Create a Grouping node. This allows you to set balanced pairs of parentheses around your SQL. ==== Arguments * +expr+ - The expression to group. ==== Example Post.where.has{_([summary, description]).in(...)} #=> SELECT "posts".* FROM "posts" WHERE ("posts"."summary", "posts"."description") IN (...)" Post.select{[id, _(Comment.where.has{post_id == posts.id}.selecting{COUNT(id)})]}.as('comment_count')} #=> SELECT "posts"."id", (SELECT COUNT("comments"."id") FROM "comments" WHERE "comments.post_id" = "posts"."id") AS "comment_count" FROM "posts"
[ "Create", "a", "Grouping", "node", ".", "This", "allows", "you", "to", "set", "balanced", "pairs", "of", "parentheses", "around", "your", "SQL", "." ]
a71a46290f49261071031b3f5a868d574f2e96c8
https://github.com/rzane/baby_squeel/blob/a71a46290f49261071031b3f5a868d574f2e96c8/lib/baby_squeel/dsl.rb#L32-L35
train
ErwinM/acts_as_tenant
lib/acts_as_tenant/controller_extensions.rb
ActsAsTenant.ControllerExtensions.set_current_tenant_by_subdomain
def set_current_tenant_by_subdomain(tenant = :account, column = :subdomain ) self.class_eval do cattr_accessor :tenant_class, :tenant_column end self.tenant_class = tenant.to_s.camelcase.constantize self.tenant_column = column.to_sym self.class_eval do before_action :find_tenant_by_subdomain helper_method :current_tenant if respond_to?(:helper_method) private def find_tenant_by_subdomain if request.subdomains.last ActsAsTenant.current_tenant = tenant_class.where(tenant_column => request.subdomains.last.downcase).first end end def current_tenant ActsAsTenant.current_tenant end end end
ruby
def set_current_tenant_by_subdomain(tenant = :account, column = :subdomain ) self.class_eval do cattr_accessor :tenant_class, :tenant_column end self.tenant_class = tenant.to_s.camelcase.constantize self.tenant_column = column.to_sym self.class_eval do before_action :find_tenant_by_subdomain helper_method :current_tenant if respond_to?(:helper_method) private def find_tenant_by_subdomain if request.subdomains.last ActsAsTenant.current_tenant = tenant_class.where(tenant_column => request.subdomains.last.downcase).first end end def current_tenant ActsAsTenant.current_tenant end end end
[ "def", "set_current_tenant_by_subdomain", "(", "tenant", "=", ":account", ",", "column", "=", ":subdomain", ")", "self", ".", "class_eval", "do", "cattr_accessor", ":tenant_class", ",", ":tenant_column", "end", "self", ".", "tenant_class", "=", "tenant", ".", "to_s", ".", "camelcase", ".", "constantize", "self", ".", "tenant_column", "=", "column", ".", "to_sym", "self", ".", "class_eval", "do", "before_action", ":find_tenant_by_subdomain", "helper_method", ":current_tenant", "if", "respond_to?", "(", ":helper_method", ")", "private", "def", "find_tenant_by_subdomain", "if", "request", ".", "subdomains", ".", "last", "ActsAsTenant", ".", "current_tenant", "=", "tenant_class", ".", "where", "(", "tenant_column", "=>", "request", ".", "subdomains", ".", "last", ".", "downcase", ")", ".", "first", "end", "end", "def", "current_tenant", "ActsAsTenant", ".", "current_tenant", "end", "end", "end" ]
this method allows setting the current_tenant by reading the subdomain and looking it up in the tenant-model passed to the method. The method will look for the subdomain in a column referenced by the second argument.
[ "this", "method", "allows", "setting", "the", "current_tenant", "by", "reading", "the", "subdomain", "and", "looking", "it", "up", "in", "the", "tenant", "-", "model", "passed", "to", "the", "method", ".", "The", "method", "will", "look", "for", "the", "subdomain", "in", "a", "column", "referenced", "by", "the", "second", "argument", "." ]
6014ca8d670a4cbc5380dc3278ed985a80fae791
https://github.com/ErwinM/acts_as_tenant/blob/6014ca8d670a4cbc5380dc3278ed985a80fae791/lib/acts_as_tenant/controller_extensions.rb#L7-L32
train
ErwinM/acts_as_tenant
lib/acts_as_tenant/controller_extensions.rb
ActsAsTenant.ControllerExtensions.set_current_tenant_through_filter
def set_current_tenant_through_filter self.class_eval do helper_method :current_tenant if respond_to?(:helper_method) private def set_current_tenant(current_tenant_object) ActsAsTenant.current_tenant = current_tenant_object end def current_tenant ActsAsTenant.current_tenant end end end
ruby
def set_current_tenant_through_filter self.class_eval do helper_method :current_tenant if respond_to?(:helper_method) private def set_current_tenant(current_tenant_object) ActsAsTenant.current_tenant = current_tenant_object end def current_tenant ActsAsTenant.current_tenant end end end
[ "def", "set_current_tenant_through_filter", "self", ".", "class_eval", "do", "helper_method", ":current_tenant", "if", "respond_to?", "(", ":helper_method", ")", "private", "def", "set_current_tenant", "(", "current_tenant_object", ")", "ActsAsTenant", ".", "current_tenant", "=", "current_tenant_object", "end", "def", "current_tenant", "ActsAsTenant", ".", "current_tenant", "end", "end", "end" ]
This method sets up a method that allows manual setting of the current_tenant. This method should be used in a before_action. In addition, a helper is setup that returns the current_tenant
[ "This", "method", "sets", "up", "a", "method", "that", "allows", "manual", "setting", "of", "the", "current_tenant", ".", "This", "method", "should", "be", "used", "in", "a", "before_action", ".", "In", "addition", "a", "helper", "is", "setup", "that", "returns", "the", "current_tenant" ]
6014ca8d670a4cbc5380dc3278ed985a80fae791
https://github.com/ErwinM/acts_as_tenant/blob/6014ca8d670a4cbc5380dc3278ed985a80fae791/lib/acts_as_tenant/controller_extensions.rb#L70-L83
train
mojombo/god
lib/god/metric.rb
God.Metric.condition
def condition(kind) # Create the condition. begin c = Condition.generate(kind, self.watch) rescue NoSuchConditionError => e abort e.message end # Send to block so config can set attributes. yield(c) if block_given? # Prepare the condition. c.prepare # Test generic and specific validity. unless Condition.valid?(c) && c.valid? abort "Exiting on invalid condition" end # Inherit interval from watch if no poll condition specific interval was # set. if c.kind_of?(PollCondition) && !c.interval if self.watch.interval c.interval = self.watch.interval else abort "No interval set for Condition '#{c.class.name}' in Watch " + "'#{self.watch.name}', and no default Watch interval from " + "which to inherit." end end # Add the condition to the list. self.conditions << c end
ruby
def condition(kind) # Create the condition. begin c = Condition.generate(kind, self.watch) rescue NoSuchConditionError => e abort e.message end # Send to block so config can set attributes. yield(c) if block_given? # Prepare the condition. c.prepare # Test generic and specific validity. unless Condition.valid?(c) && c.valid? abort "Exiting on invalid condition" end # Inherit interval from watch if no poll condition specific interval was # set. if c.kind_of?(PollCondition) && !c.interval if self.watch.interval c.interval = self.watch.interval else abort "No interval set for Condition '#{c.class.name}' in Watch " + "'#{self.watch.name}', and no default Watch interval from " + "which to inherit." end end # Add the condition to the list. self.conditions << c end
[ "def", "condition", "(", "kind", ")", "# Create the condition.", "begin", "c", "=", "Condition", ".", "generate", "(", "kind", ",", "self", ".", "watch", ")", "rescue", "NoSuchConditionError", "=>", "e", "abort", "e", ".", "message", "end", "# Send to block so config can set attributes.", "yield", "(", "c", ")", "if", "block_given?", "# Prepare the condition.", "c", ".", "prepare", "# Test generic and specific validity.", "unless", "Condition", ".", "valid?", "(", "c", ")", "&&", "c", ".", "valid?", "abort", "\"Exiting on invalid condition\"", "end", "# Inherit interval from watch if no poll condition specific interval was", "# set.", "if", "c", ".", "kind_of?", "(", "PollCondition", ")", "&&", "!", "c", ".", "interval", "if", "self", ".", "watch", ".", "interval", "c", ".", "interval", "=", "self", ".", "watch", ".", "interval", "else", "abort", "\"No interval set for Condition '#{c.class.name}' in Watch \"", "+", "\"'#{self.watch.name}', and no default Watch interval from \"", "+", "\"which to inherit.\"", "end", "end", "# Add the condition to the list.", "self", ".", "conditions", "<<", "c", "end" ]
Initialize a new Metric. watch - The Watch. destination - The optional destination Hash in canonical hash form. Public: Instantiate the given Condition and pass it into the optional block. Attributes of the condition must be set in the config file. kind - The Symbol name of the condition. Returns nothing.
[ "Initialize", "a", "new", "Metric", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/metric.rb#L32-L65
train
mojombo/god
lib/god/socket.rb
God.Socket.start
def start begin @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") rescue Errno::EADDRINUSE applog(nil, :info, "Socket already in use") server = DRbObject.new(nil, self.socket) begin Timeout.timeout(5) do server.ping end abort "Socket #{self.socket} already in use by another instance of god" rescue StandardError, Timeout::Error applog(nil, :info, "Socket is stale, reopening") File.delete(self.socket_file) rescue nil @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") end end if File.exists?(self.socket_file) if @user user_method = @user.is_a?(Integer) ? :getpwuid : :getpwnam uid = Etc.send(user_method, @user).uid gid = Etc.send(user_method, @user).gid end if @group group_method = @group.is_a?(Integer) ? :getgrgid : :getgrnam gid = Etc.send(group_method, @group).gid end File.chmod(Integer(@perm), socket_file) if @perm File.chown(uid, gid, socket_file) if uid or gid end end
ruby
def start begin @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") rescue Errno::EADDRINUSE applog(nil, :info, "Socket already in use") server = DRbObject.new(nil, self.socket) begin Timeout.timeout(5) do server.ping end abort "Socket #{self.socket} already in use by another instance of god" rescue StandardError, Timeout::Error applog(nil, :info, "Socket is stale, reopening") File.delete(self.socket_file) rescue nil @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") end end if File.exists?(self.socket_file) if @user user_method = @user.is_a?(Integer) ? :getpwuid : :getpwnam uid = Etc.send(user_method, @user).uid gid = Etc.send(user_method, @user).gid end if @group group_method = @group.is_a?(Integer) ? :getgrgid : :getgrnam gid = Etc.send(group_method, @group).gid end File.chmod(Integer(@perm), socket_file) if @perm File.chown(uid, gid, socket_file) if uid or gid end end
[ "def", "start", "begin", "@drb", "||=", "DRb", ".", "start_service", "(", "self", ".", "socket", ",", "self", ")", "applog", "(", "nil", ",", ":info", ",", "\"Started on #{DRb.uri}\"", ")", "rescue", "Errno", "::", "EADDRINUSE", "applog", "(", "nil", ",", ":info", ",", "\"Socket already in use\"", ")", "server", "=", "DRbObject", ".", "new", "(", "nil", ",", "self", ".", "socket", ")", "begin", "Timeout", ".", "timeout", "(", "5", ")", "do", "server", ".", "ping", "end", "abort", "\"Socket #{self.socket} already in use by another instance of god\"", "rescue", "StandardError", ",", "Timeout", "::", "Error", "applog", "(", "nil", ",", ":info", ",", "\"Socket is stale, reopening\"", ")", "File", ".", "delete", "(", "self", ".", "socket_file", ")", "rescue", "nil", "@drb", "||=", "DRb", ".", "start_service", "(", "self", ".", "socket", ",", "self", ")", "applog", "(", "nil", ",", ":info", ",", "\"Started on #{DRb.uri}\"", ")", "end", "end", "if", "File", ".", "exists?", "(", "self", ".", "socket_file", ")", "if", "@user", "user_method", "=", "@user", ".", "is_a?", "(", "Integer", ")", "?", ":getpwuid", ":", ":getpwnam", "uid", "=", "Etc", ".", "send", "(", "user_method", ",", "@user", ")", ".", "uid", "gid", "=", "Etc", ".", "send", "(", "user_method", ",", "@user", ")", ".", "gid", "end", "if", "@group", "group_method", "=", "@group", ".", "is_a?", "(", "Integer", ")", "?", ":getgrgid", ":", ":getgrnam", "gid", "=", "Etc", ".", "send", "(", "group_method", ",", "@group", ")", ".", "gid", "end", "File", ".", "chmod", "(", "Integer", "(", "@perm", ")", ",", "socket_file", ")", "if", "@perm", "File", ".", "chown", "(", "uid", ",", "gid", ",", "socket_file", ")", "if", "uid", "or", "gid", "end", "end" ]
Start the DRb server. Abort if there is already a running god instance on the socket. Returns nothing
[ "Start", "the", "DRb", "server", ".", "Abort", "if", "there", "is", "already", "a", "running", "god", "instance", "on", "the", "socket", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/socket.rb#L75-L110
train
mojombo/god
lib/god/task.rb
God.Task.valid?
def valid? valid = true # A name must be specified. if self.name.nil? valid = false applog(self, :error, "No name String was specified.") end # Valid states must be specified. if self.valid_states.nil? valid = false applog(self, :error, "No valid_states Array or Symbols was specified.") end # An initial state must be specified. if self.initial_state.nil? valid = false applog(self, :error, "No initial_state Symbol was specified.") end valid end
ruby
def valid? valid = true # A name must be specified. if self.name.nil? valid = false applog(self, :error, "No name String was specified.") end # Valid states must be specified. if self.valid_states.nil? valid = false applog(self, :error, "No valid_states Array or Symbols was specified.") end # An initial state must be specified. if self.initial_state.nil? valid = false applog(self, :error, "No initial_state Symbol was specified.") end valid end
[ "def", "valid?", "valid", "=", "true", "# A name must be specified.", "if", "self", ".", "name", ".", "nil?", "valid", "=", "false", "applog", "(", "self", ",", ":error", ",", "\"No name String was specified.\"", ")", "end", "# Valid states must be specified.", "if", "self", ".", "valid_states", ".", "nil?", "valid", "=", "false", "applog", "(", "self", ",", ":error", ",", "\"No valid_states Array or Symbols was specified.\"", ")", "end", "# An initial state must be specified.", "if", "self", ".", "initial_state", ".", "nil?", "valid", "=", "false", "applog", "(", "self", ",", ":error", ",", "\"No initial_state Symbol was specified.\"", ")", "end", "valid", "end" ]
Verify that the minimum set of configuration requirements has been met. Returns true if valid, false if not.
[ "Verify", "that", "the", "minimum", "set", "of", "configuration", "requirements", "has", "been", "met", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L66-L88
train
mojombo/god
lib/god/task.rb
God.Task.move
def move(to_state) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:move, [to_state]) else # Called from within Driver. Record original info. orig_to_state = to_state from_state = self.state # Log. msg = "#{self.name} move '#{from_state}' to '#{to_state}'" applog(self, :info, msg) # Cleanup from current state. self.driver.clear_events self.metrics[from_state].each { |m| m.disable } if to_state == :unmonitored self.metrics[nil].each { |m| m.disable } end # Perform action. self.action(to_state) # Enable simple mode. if [:start, :restart].include?(to_state) && self.metrics[to_state].empty? to_state = :up end # Move to new state. self.metrics[to_state].each { |m| m.enable } # If no from state, enable lifecycle metric. if from_state == :unmonitored self.metrics[nil].each { |m| m.enable } end # Set state. self.state = to_state # Broadcast to interested TriggerConditions. Trigger.broadcast(self, :state_change, [from_state, orig_to_state]) # Log. msg = "#{self.name} moved '#{from_state}' to '#{to_state}'" applog(self, :info, msg) end self end
ruby
def move(to_state) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:move, [to_state]) else # Called from within Driver. Record original info. orig_to_state = to_state from_state = self.state # Log. msg = "#{self.name} move '#{from_state}' to '#{to_state}'" applog(self, :info, msg) # Cleanup from current state. self.driver.clear_events self.metrics[from_state].each { |m| m.disable } if to_state == :unmonitored self.metrics[nil].each { |m| m.disable } end # Perform action. self.action(to_state) # Enable simple mode. if [:start, :restart].include?(to_state) && self.metrics[to_state].empty? to_state = :up end # Move to new state. self.metrics[to_state].each { |m| m.enable } # If no from state, enable lifecycle metric. if from_state == :unmonitored self.metrics[nil].each { |m| m.enable } end # Set state. self.state = to_state # Broadcast to interested TriggerConditions. Trigger.broadcast(self, :state_change, [from_state, orig_to_state]) # Log. msg = "#{self.name} moved '#{from_state}' to '#{to_state}'" applog(self, :info, msg) end self end
[ "def", "move", "(", "to_state", ")", "if", "!", "self", ".", "driver", ".", "in_driver_context?", "# Called from outside Driver. Send an async message to Driver.", "self", ".", "driver", ".", "message", "(", ":move", ",", "[", "to_state", "]", ")", "else", "# Called from within Driver. Record original info.", "orig_to_state", "=", "to_state", "from_state", "=", "self", ".", "state", "# Log.", "msg", "=", "\"#{self.name} move '#{from_state}' to '#{to_state}'\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "# Cleanup from current state.", "self", ".", "driver", ".", "clear_events", "self", ".", "metrics", "[", "from_state", "]", ".", "each", "{", "|", "m", "|", "m", ".", "disable", "}", "if", "to_state", "==", ":unmonitored", "self", ".", "metrics", "[", "nil", "]", ".", "each", "{", "|", "m", "|", "m", ".", "disable", "}", "end", "# Perform action.", "self", ".", "action", "(", "to_state", ")", "# Enable simple mode.", "if", "[", ":start", ",", ":restart", "]", ".", "include?", "(", "to_state", ")", "&&", "self", ".", "metrics", "[", "to_state", "]", ".", "empty?", "to_state", "=", ":up", "end", "# Move to new state.", "self", ".", "metrics", "[", "to_state", "]", ".", "each", "{", "|", "m", "|", "m", ".", "enable", "}", "# If no from state, enable lifecycle metric.", "if", "from_state", "==", ":unmonitored", "self", ".", "metrics", "[", "nil", "]", ".", "each", "{", "|", "m", "|", "m", ".", "enable", "}", "end", "# Set state.", "self", ".", "state", "=", "to_state", "# Broadcast to interested TriggerConditions.", "Trigger", ".", "broadcast", "(", "self", ",", ":state_change", ",", "[", "from_state", ",", "orig_to_state", "]", ")", "# Log.", "msg", "=", "\"#{self.name} moved '#{from_state}' to '#{to_state}'\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "end", "self", "end" ]
Move to the given state. to_state - The Symbol representing the state to move to. Returns this Task.
[ "Move", "to", "the", "given", "state", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L194-L242
train
mojombo/god
lib/god/task.rb
God.Task.action
def action(a, c = nil) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:action, [a, c]) else # Called from within Driver. if self.respond_to?(a) command = self.send(a) case command when String msg = "#{self.name} #{a}: #{command}" applog(self, :info, msg) system(command) when Proc msg = "#{self.name} #{a}: lambda" applog(self, :info, msg) command.call else raise NotImplementedError end end end end
ruby
def action(a, c = nil) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:action, [a, c]) else # Called from within Driver. if self.respond_to?(a) command = self.send(a) case command when String msg = "#{self.name} #{a}: #{command}" applog(self, :info, msg) system(command) when Proc msg = "#{self.name} #{a}: lambda" applog(self, :info, msg) command.call else raise NotImplementedError end end end end
[ "def", "action", "(", "a", ",", "c", "=", "nil", ")", "if", "!", "self", ".", "driver", ".", "in_driver_context?", "# Called from outside Driver. Send an async message to Driver.", "self", ".", "driver", ".", "message", "(", ":action", ",", "[", "a", ",", "c", "]", ")", "else", "# Called from within Driver.", "if", "self", ".", "respond_to?", "(", "a", ")", "command", "=", "self", ".", "send", "(", "a", ")", "case", "command", "when", "String", "msg", "=", "\"#{self.name} #{a}: #{command}\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "system", "(", "command", ")", "when", "Proc", "msg", "=", "\"#{self.name} #{a}: lambda\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "command", ".", "call", "else", "raise", "NotImplementedError", "end", "end", "end", "end" ]
Perform the given action. a - The Symbol action. c - The Condition. Returns this Task.
[ "Perform", "the", "given", "action", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L284-L309
train
mojombo/god
lib/god/task.rb
God.Task.handle_event
def handle_event(condition) # Lookup metric. metric = self.directory[condition] # Log. messages = self.log_line(self, metric, condition, true) # Notify. if condition.notify self.notify(condition, messages.last) end # Get the destination. dest = if condition.transition # Condition override. condition.transition else # Regular. metric.destination && metric.destination[true] end if dest self.move(dest) end end
ruby
def handle_event(condition) # Lookup metric. metric = self.directory[condition] # Log. messages = self.log_line(self, metric, condition, true) # Notify. if condition.notify self.notify(condition, messages.last) end # Get the destination. dest = if condition.transition # Condition override. condition.transition else # Regular. metric.destination && metric.destination[true] end if dest self.move(dest) end end
[ "def", "handle_event", "(", "condition", ")", "# Lookup metric.", "metric", "=", "self", ".", "directory", "[", "condition", "]", "# Log.", "messages", "=", "self", ".", "log_line", "(", "self", ",", "metric", ",", "condition", ",", "true", ")", "# Notify.", "if", "condition", ".", "notify", "self", ".", "notify", "(", "condition", ",", "messages", ".", "last", ")", "end", "# Get the destination.", "dest", "=", "if", "condition", ".", "transition", "# Condition override.", "condition", ".", "transition", "else", "# Regular.", "metric", ".", "destination", "&&", "metric", ".", "destination", "[", "true", "]", "end", "if", "dest", "self", ".", "move", "(", "dest", ")", "end", "end" ]
Asynchronously evaluate and handle the given event condition. Handles logging notifications, and moving to the new state if necessary. condition - The Condition to handle. Returns nothing.
[ "Asynchronously", "evaluate", "and", "handle", "the", "given", "event", "condition", ".", "Handles", "logging", "notifications", "and", "moving", "to", "the", "new", "state", "if", "necessary", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L421-L446
train
mojombo/god
lib/god/task.rb
God.Task.log_line
def log_line(watch, metric, condition, result) status = if self.trigger?(metric, result) "[trigger]" else "[ok]" end messages = [] # Log info if available. if condition.info Array(condition.info).each do |condition_info| messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})" applog(watch, :info, messages.last) end else messages << "#{watch.name} #{status} (#{condition.base_name})" applog(watch, :info, messages.last) end # Log. debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition) applog(watch, :debug, debug_message) messages end
ruby
def log_line(watch, metric, condition, result) status = if self.trigger?(metric, result) "[trigger]" else "[ok]" end messages = [] # Log info if available. if condition.info Array(condition.info).each do |condition_info| messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})" applog(watch, :info, messages.last) end else messages << "#{watch.name} #{status} (#{condition.base_name})" applog(watch, :info, messages.last) end # Log. debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition) applog(watch, :debug, debug_message) messages end
[ "def", "log_line", "(", "watch", ",", "metric", ",", "condition", ",", "result", ")", "status", "=", "if", "self", ".", "trigger?", "(", "metric", ",", "result", ")", "\"[trigger]\"", "else", "\"[ok]\"", "end", "messages", "=", "[", "]", "# Log info if available.", "if", "condition", ".", "info", "Array", "(", "condition", ".", "info", ")", ".", "each", "do", "|", "condition_info", "|", "messages", "<<", "\"#{watch.name} #{status} #{condition_info} (#{condition.base_name})\"", "applog", "(", "watch", ",", ":info", ",", "messages", ".", "last", ")", "end", "else", "messages", "<<", "\"#{watch.name} #{status} (#{condition.base_name})\"", "applog", "(", "watch", ",", ":info", ",", "messages", ".", "last", ")", "end", "# Log.", "debug_message", "=", "watch", ".", "name", "+", "' '", "+", "condition", ".", "base_name", "+", "\" [#{result}] \"", "+", "self", ".", "dest_desc", "(", "metric", ",", "condition", ")", "applog", "(", "watch", ",", ":debug", ",", "debug_message", ")", "messages", "end" ]
Log info about the condition and return the list of messages logged. watch - The Watch. metric - The Metric. condition - The Condition. result - The Boolean result of the condition test evaluation. Returns the Array of String messages.
[ "Log", "info", "about", "the", "condition", "and", "return", "the", "list", "of", "messages", "logged", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L466-L492
train
mojombo/god
lib/god/task.rb
God.Task.dest_desc
def dest_desc(metric, condition) if condition.transition {true => condition.transition}.inspect else if metric.destination metric.destination.inspect else 'none' end end end
ruby
def dest_desc(metric, condition) if condition.transition {true => condition.transition}.inspect else if metric.destination metric.destination.inspect else 'none' end end end
[ "def", "dest_desc", "(", "metric", ",", "condition", ")", "if", "condition", ".", "transition", "{", "true", "=>", "condition", ".", "transition", "}", ".", "inspect", "else", "if", "metric", ".", "destination", "metric", ".", "destination", ".", "inspect", "else", "'none'", "end", "end", "end" ]
Format the destination specification for use in debug logging. metric - The Metric. condition - The Condition. Returns the formatted String.
[ "Format", "the", "destination", "specification", "for", "use", "in", "debug", "logging", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L500-L510
train
mojombo/god
lib/god/task.rb
God.Task.notify
def notify(condition, message) spec = Contact.normalize(condition.notify) unmatched = [] # Resolve contacts. resolved_contacts = spec[:contacts].inject([]) do |acc, contact_name_or_group| cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group]) unmatched << contact_name_or_group if cons.empty? acc += cons acc end # Warn about unmatched contacts. unless unmatched.empty? msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'" applog(condition.watch, :warn, msg) end # Notify each contact. resolved_contacts.each do |c| host = `hostname`.chomp rescue 'none' begin c.notify(message, Time.now, spec[:priority], spec[:category], host) msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})" applog(condition.watch, :info, msg % []) rescue Exception => e applog(condition.watch, :error, "#{e.message} #{e.backtrace}") msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})" applog(condition.watch, :error, msg % []) end end end
ruby
def notify(condition, message) spec = Contact.normalize(condition.notify) unmatched = [] # Resolve contacts. resolved_contacts = spec[:contacts].inject([]) do |acc, contact_name_or_group| cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group]) unmatched << contact_name_or_group if cons.empty? acc += cons acc end # Warn about unmatched contacts. unless unmatched.empty? msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'" applog(condition.watch, :warn, msg) end # Notify each contact. resolved_contacts.each do |c| host = `hostname`.chomp rescue 'none' begin c.notify(message, Time.now, spec[:priority], spec[:category], host) msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})" applog(condition.watch, :info, msg % []) rescue Exception => e applog(condition.watch, :error, "#{e.message} #{e.backtrace}") msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})" applog(condition.watch, :error, msg % []) end end end
[ "def", "notify", "(", "condition", ",", "message", ")", "spec", "=", "Contact", ".", "normalize", "(", "condition", ".", "notify", ")", "unmatched", "=", "[", "]", "# Resolve contacts.", "resolved_contacts", "=", "spec", "[", ":contacts", "]", ".", "inject", "(", "[", "]", ")", "do", "|", "acc", ",", "contact_name_or_group", "|", "cons", "=", "Array", "(", "God", ".", "contacts", "[", "contact_name_or_group", "]", "||", "God", ".", "contact_groups", "[", "contact_name_or_group", "]", ")", "unmatched", "<<", "contact_name_or_group", "if", "cons", ".", "empty?", "acc", "+=", "cons", "acc", "end", "# Warn about unmatched contacts.", "unless", "unmatched", ".", "empty?", "msg", "=", "\"#{condition.watch.name} no matching contacts for '#{unmatched.join(\", \")}'\"", "applog", "(", "condition", ".", "watch", ",", ":warn", ",", "msg", ")", "end", "# Notify each contact.", "resolved_contacts", ".", "each", "do", "|", "c", "|", "host", "=", "`", "`", ".", "chomp", "rescue", "'none'", "begin", "c", ".", "notify", "(", "message", ",", "Time", ".", "now", ",", "spec", "[", ":priority", "]", ",", "spec", "[", ":category", "]", ",", "host", ")", "msg", "=", "\"#{condition.watch.name} #{c.info ? c.info : \"notification sent for contact: #{c.name}\"} (#{c.base_name})\"", "applog", "(", "condition", ".", "watch", ",", ":info", ",", "msg", "%", "[", "]", ")", "rescue", "Exception", "=>", "e", "applog", "(", "condition", ".", "watch", ",", ":error", ",", "\"#{e.message} #{e.backtrace}\"", ")", "msg", "=", "\"#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})\"", "applog", "(", "condition", ".", "watch", ",", ":error", ",", "msg", "%", "[", "]", ")", "end", "end", "end" ]
Notify all recipients of the given condition with the specified message. condition - The Condition. message - The String message to send. Returns nothing.
[ "Notify", "all", "recipients", "of", "the", "given", "condition", "with", "the", "specified", "message", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/task.rb#L518-L550
train
mojombo/god
lib/god/logger.rb
God.Logger.level=
def level=(lev) SysLogger.level = SimpleLogger::CONSTANT_TO_SYMBOL[lev] if Logger.syslog super(lev) end
ruby
def level=(lev) SysLogger.level = SimpleLogger::CONSTANT_TO_SYMBOL[lev] if Logger.syslog super(lev) end
[ "def", "level", "=", "(", "lev", ")", "SysLogger", ".", "level", "=", "SimpleLogger", "::", "CONSTANT_TO_SYMBOL", "[", "lev", "]", "if", "Logger", ".", "syslog", "super", "(", "lev", ")", "end" ]
Instantiate a new Logger object
[ "Instantiate", "a", "new", "Logger", "object" ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/logger.rb#L26-L29
train
mojombo/god
lib/god/logger.rb
God.Logger.watch_log_since
def watch_log_since(watch_name, since) # initialize watch log if necessary self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) # get and join lines since given time @mutex.synchronize do @spool = Time.now self.logs[watch_name].select do |x| x.first > since end.map do |x| x[1] end.join end end
ruby
def watch_log_since(watch_name, since) # initialize watch log if necessary self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) # get and join lines since given time @mutex.synchronize do @spool = Time.now self.logs[watch_name].select do |x| x.first > since end.map do |x| x[1] end.join end end
[ "def", "watch_log_since", "(", "watch_name", ",", "since", ")", "# initialize watch log if necessary", "self", ".", "logs", "[", "watch_name", "]", "||=", "Timeline", ".", "new", "(", "God", "::", "LOG_BUFFER_SIZE_DEFAULT", ")", "# get and join lines since given time", "@mutex", ".", "synchronize", "do", "@spool", "=", "Time", ".", "now", "self", ".", "logs", "[", "watch_name", "]", ".", "select", "do", "|", "x", "|", "x", ".", "first", ">", "since", "end", ".", "map", "do", "|", "x", "|", "x", "[", "1", "]", "end", ".", "join", "end", "end" ]
Get all log output for a given Watch since a certain Time. +watch_name+ is the String name of the Watch +since+ is the Time since which to fetch log lines Returns String
[ "Get", "all", "log", "output", "for", "a", "given", "Watch", "since", "a", "certain", "Time", ".", "+", "watch_name", "+", "is", "the", "String", "name", "of", "the", "Watch", "+", "since", "+", "is", "the", "Time", "since", "which", "to", "fetch", "log", "lines" ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/logger.rb#L70-L83
train
mojombo/god
lib/god/process.rb
God.Process.pid
def pid contents = File.read(self.pid_file).strip rescue '' real_pid = contents =~ /^\d+$/ ? contents.to_i : nil if real_pid @pid = real_pid real_pid else @pid end end
ruby
def pid contents = File.read(self.pid_file).strip rescue '' real_pid = contents =~ /^\d+$/ ? contents.to_i : nil if real_pid @pid = real_pid real_pid else @pid end end
[ "def", "pid", "contents", "=", "File", ".", "read", "(", "self", ".", "pid_file", ")", ".", "strip", "rescue", "''", "real_pid", "=", "contents", "=~", "/", "\\d", "/", "?", "contents", ".", "to_i", ":", "nil", "if", "real_pid", "@pid", "=", "real_pid", "real_pid", "else", "@pid", "end", "end" ]
Fetch the PID from pid_file. If the pid_file does not exist, then use the PID from the last time it was read. If it has never been read, then return nil. Returns Integer(pid) or nil
[ "Fetch", "the", "PID", "from", "pid_file", ".", "If", "the", "pid_file", "does", "not", "exist", "then", "use", "the", "PID", "from", "the", "last", "time", "it", "was", "read", ".", "If", "it", "has", "never", "been", "read", "then", "return", "nil", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/process.rb#L171-L181
train
mojombo/god
lib/god/process.rb
God.Process.signal
def signal(sig) sig = sig.to_i if sig.to_i != 0 applog(self, :info, "#{self.name} sending signal '#{sig}' to pid #{self.pid}") ::Process.kill(sig, self.pid) rescue nil end
ruby
def signal(sig) sig = sig.to_i if sig.to_i != 0 applog(self, :info, "#{self.name} sending signal '#{sig}' to pid #{self.pid}") ::Process.kill(sig, self.pid) rescue nil end
[ "def", "signal", "(", "sig", ")", "sig", "=", "sig", ".", "to_i", "if", "sig", ".", "to_i", "!=", "0", "applog", "(", "self", ",", ":info", ",", "\"#{self.name} sending signal '#{sig}' to pid #{self.pid}\"", ")", "::", "Process", ".", "kill", "(", "sig", ",", "self", ".", "pid", ")", "rescue", "nil", "end" ]
Send the given signal to this process. Returns nothing
[ "Send", "the", "given", "signal", "to", "this", "process", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/process.rb#L186-L190
train
mojombo/god
lib/god/process.rb
God.Process.ensure_stop
def ensure_stop applog(self, :warn, "#{self.name} ensuring stop...") unless self.pid applog(self, :warn, "#{self.name} stop called but pid is uknown") return end # Poll to see if it's dead @stop_timeout.times do begin ::Process.kill(0, self.pid) rescue Errno::ESRCH # It died. Good. return end sleep 1 end # last resort ::Process.kill('KILL', self.pid) rescue nil applog(self, :warn, "#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL") end
ruby
def ensure_stop applog(self, :warn, "#{self.name} ensuring stop...") unless self.pid applog(self, :warn, "#{self.name} stop called but pid is uknown") return end # Poll to see if it's dead @stop_timeout.times do begin ::Process.kill(0, self.pid) rescue Errno::ESRCH # It died. Good. return end sleep 1 end # last resort ::Process.kill('KILL', self.pid) rescue nil applog(self, :warn, "#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL") end
[ "def", "ensure_stop", "applog", "(", "self", ",", ":warn", ",", "\"#{self.name} ensuring stop...\"", ")", "unless", "self", ".", "pid", "applog", "(", "self", ",", ":warn", ",", "\"#{self.name} stop called but pid is uknown\"", ")", "return", "end", "# Poll to see if it's dead", "@stop_timeout", ".", "times", "do", "begin", "::", "Process", ".", "kill", "(", "0", ",", "self", ".", "pid", ")", "rescue", "Errno", "::", "ESRCH", "# It died. Good.", "return", "end", "sleep", "1", "end", "# last resort", "::", "Process", ".", "kill", "(", "'KILL'", ",", "self", ".", "pid", ")", "rescue", "nil", "applog", "(", "self", ",", ":warn", ",", "\"#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL\"", ")", "end" ]
Ensure that a stop command actually stops the process. Force kill if necessary. Returns nothing
[ "Ensure", "that", "a", "stop", "command", "actually", "stops", "the", "process", ".", "Force", "kill", "if", "necessary", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/process.rb#L349-L372
train
mojombo/god
lib/god/driver.rb
God.DriverEventQueue.pop
def pop @monitor.synchronize do if @events.empty? raise ThreadError, "queue empty" if @shutdown @resource.wait else delay = @events.first.at - Time.now @resource.wait(delay) if delay > 0 end @events.shift end end
ruby
def pop @monitor.synchronize do if @events.empty? raise ThreadError, "queue empty" if @shutdown @resource.wait else delay = @events.first.at - Time.now @resource.wait(delay) if delay > 0 end @events.shift end end
[ "def", "pop", "@monitor", ".", "synchronize", "do", "if", "@events", ".", "empty?", "raise", "ThreadError", ",", "\"queue empty\"", "if", "@shutdown", "@resource", ".", "wait", "else", "delay", "=", "@events", ".", "first", ".", "at", "-", "Time", ".", "now", "@resource", ".", "wait", "(", "delay", ")", "if", "delay", ">", "0", "end", "@events", ".", "shift", "end", "end" ]
Wait until the queue has something due, pop it off the queue, and return it. Returns the popped event.
[ "Wait", "until", "the", "queue", "has", "something", "due", "pop", "it", "off", "the", "queue", "and", "return", "it", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/driver.rb#L116-L128
train
mojombo/god
lib/god/driver.rb
God.Driver.schedule
def schedule(condition, delay = condition.interval) applog(nil, :debug, "driver schedule #{condition} in #{delay} seconds") @events.push(DriverEvent.new(delay, @task, condition)) end
ruby
def schedule(condition, delay = condition.interval) applog(nil, :debug, "driver schedule #{condition} in #{delay} seconds") @events.push(DriverEvent.new(delay, @task, condition)) end
[ "def", "schedule", "(", "condition", ",", "delay", "=", "condition", ".", "interval", ")", "applog", "(", "nil", ",", ":debug", ",", "\"driver schedule #{condition} in #{delay} seconds\"", ")", "@events", ".", "push", "(", "DriverEvent", ".", "new", "(", "delay", ",", "@task", ",", "condition", ")", ")", "end" ]
Create and schedule a new DriverEvent. condition - The Condition. delay - The Numeric number of seconds to delay (default: interval defined in condition). Returns nothing.
[ "Create", "and", "schedule", "a", "new", "DriverEvent", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/driver.rb#L232-L236
train
mojombo/god
lib/god/watch.rb
God.Watch.call_action
def call_action(condition, action) # Before. before_items = self.behaviors before_items += [condition] if condition before_items.each do |b| info = b.send("before_#{action}") if info msg = "#{self.name} before_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end # Log. if self.send(action) msg = "#{self.name} #{action}: #{self.send(action).to_s}" applog(self, :info, msg) end # Execute. @process.call_action(action) # After. after_items = self.behaviors after_items += [condition] if condition after_items.each do |b| info = b.send("after_#{action}") if info msg = "#{self.name} after_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end end
ruby
def call_action(condition, action) # Before. before_items = self.behaviors before_items += [condition] if condition before_items.each do |b| info = b.send("before_#{action}") if info msg = "#{self.name} before_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end # Log. if self.send(action) msg = "#{self.name} #{action}: #{self.send(action).to_s}" applog(self, :info, msg) end # Execute. @process.call_action(action) # After. after_items = self.behaviors after_items += [condition] if condition after_items.each do |b| info = b.send("after_#{action}") if info msg = "#{self.name} after_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end end
[ "def", "call_action", "(", "condition", ",", "action", ")", "# Before.", "before_items", "=", "self", ".", "behaviors", "before_items", "+=", "[", "condition", "]", "if", "condition", "before_items", ".", "each", "do", "|", "b", "|", "info", "=", "b", ".", "send", "(", "\"before_#{action}\"", ")", "if", "info", "msg", "=", "\"#{self.name} before_#{action}: #{info} (#{b.base_name})\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "end", "end", "# Log.", "if", "self", ".", "send", "(", "action", ")", "msg", "=", "\"#{self.name} #{action}: #{self.send(action).to_s}\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "end", "# Execute.", "@process", ".", "call_action", "(", "action", ")", "# After.", "after_items", "=", "self", ".", "behaviors", "after_items", "+=", "[", "condition", "]", "if", "condition", "after_items", ".", "each", "do", "|", "b", "|", "info", "=", "b", ".", "send", "(", "\"after_#{action}\"", ")", "if", "info", "msg", "=", "\"#{self.name} after_#{action}: #{info} (#{b.base_name})\"", "applog", "(", "self", ",", ":info", ",", "msg", ")", "end", "end", "end" ]
Perform the specifics of the action. condition - The Condition. action - The Symbol action. Returns nothing.
[ "Perform", "the", "specifics", "of", "the", "action", "." ]
92c06aa5f6293cf26498a306e9bb7ac856d7dca0
https://github.com/mojombo/god/blob/92c06aa5f6293cf26498a306e9bb7ac856d7dca0/lib/god/watch.rb#L286-L317
train
activeadmin/inherited_resources
lib/inherited_resources/base_helpers.rb
InheritedResources.BaseHelpers.collection
def collection get_collection_ivar || begin c = end_of_association_chain set_collection_ivar(c.respond_to?(:scoped) ? c.scoped : c.all) end end
ruby
def collection get_collection_ivar || begin c = end_of_association_chain set_collection_ivar(c.respond_to?(:scoped) ? c.scoped : c.all) end end
[ "def", "collection", "get_collection_ivar", "||", "begin", "c", "=", "end_of_association_chain", "set_collection_ivar", "(", "c", ".", "respond_to?", "(", ":scoped", ")", "?", "c", ".", "scoped", ":", "c", ".", "all", ")", "end", "end" ]
This is how the collection is loaded. You might want to overwrite this method if you want to add pagination for example. When you do that, don't forget to cache the result in an instance_variable: def collection @projects ||= end_of_association_chain.paginate(params[:page]).all end
[ "This", "is", "how", "the", "collection", "is", "loaded", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/base_helpers.rb#L22-L27
train
activeadmin/inherited_resources
lib/inherited_resources/base_helpers.rb
InheritedResources.BaseHelpers.end_of_association_chain
def end_of_association_chain #:nodoc: if chain = association_chain.last if method_for_association_chain apply_scopes_if_available(chain.send(method_for_association_chain)) else # This only happens when we specify begin_of_association_chain in # a singleton controller without parents. In this case, the chain # is exactly the begin_of_association_chain which is already an # instance and then not scopable. chain end else apply_scopes_if_available(resource_class) end end
ruby
def end_of_association_chain #:nodoc: if chain = association_chain.last if method_for_association_chain apply_scopes_if_available(chain.send(method_for_association_chain)) else # This only happens when we specify begin_of_association_chain in # a singleton controller without parents. In this case, the chain # is exactly the begin_of_association_chain which is already an # instance and then not scopable. chain end else apply_scopes_if_available(resource_class) end end
[ "def", "end_of_association_chain", "#:nodoc:", "if", "chain", "=", "association_chain", ".", "last", "if", "method_for_association_chain", "apply_scopes_if_available", "(", "chain", ".", "send", "(", "method_for_association_chain", ")", ")", "else", "# This only happens when we specify begin_of_association_chain in", "# a singleton controller without parents. In this case, the chain", "# is exactly the begin_of_association_chain which is already an", "# instance and then not scopable.", "chain", "end", "else", "apply_scopes_if_available", "(", "resource_class", ")", "end", "end" ]
This methods gets your begin_of_association_chain, join it with your parents chain and returns the scoped association.
[ "This", "methods", "gets", "your", "begin_of_association_chain", "join", "it", "with", "your", "parents", "chain", "and", "returns", "the", "scoped", "association", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/base_helpers.rb#L172-L186
train
activeadmin/inherited_resources
lib/inherited_resources/base_helpers.rb
InheritedResources.BaseHelpers.smart_collection_url
def smart_collection_url url = nil if respond_to? :index url ||= collection_url rescue nil end if respond_to? :parent, true url ||= parent_url rescue nil end url ||= root_url rescue nil end
ruby
def smart_collection_url url = nil if respond_to? :index url ||= collection_url rescue nil end if respond_to? :parent, true url ||= parent_url rescue nil end url ||= root_url rescue nil end
[ "def", "smart_collection_url", "url", "=", "nil", "if", "respond_to?", ":index", "url", "||=", "collection_url", "rescue", "nil", "end", "if", "respond_to?", ":parent", ",", "true", "url", "||=", "parent_url", "rescue", "nil", "end", "url", "||=", "root_url", "rescue", "nil", "end" ]
URL to redirect to when redirect implies collection url.
[ "URL", "to", "redirect", "to", "when", "redirect", "implies", "collection", "url", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/base_helpers.rb#L302-L311
train
activeadmin/inherited_resources
lib/inherited_resources/base_helpers.rb
InheritedResources.BaseHelpers.build_resource_params
def build_resource_params parameters = permitted_params || params rparams = [parameters[resource_request_name] || parameters[resource_instance_name] || {}] if without_protection_given? rparams << without_protection else rparams << as_role if role_given? end rparams end
ruby
def build_resource_params parameters = permitted_params || params rparams = [parameters[resource_request_name] || parameters[resource_instance_name] || {}] if without_protection_given? rparams << without_protection else rparams << as_role if role_given? end rparams end
[ "def", "build_resource_params", "parameters", "=", "permitted_params", "||", "params", "rparams", "=", "[", "parameters", "[", "resource_request_name", "]", "||", "parameters", "[", "resource_instance_name", "]", "||", "{", "}", "]", "if", "without_protection_given?", "rparams", "<<", "without_protection", "else", "rparams", "<<", "as_role", "if", "role_given?", "end", "rparams", "end" ]
extract attributes from params
[ "extract", "attributes", "from", "params" ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/base_helpers.rb#L354-L364
train
activeadmin/inherited_resources
lib/inherited_resources/class_methods.rb
InheritedResources.ClassMethods.actions
def actions(*actions_to_keep) raise ArgumentError, 'Wrong number of arguments. You have to provide which actions you want to keep.' if actions_to_keep.empty? options = actions_to_keep.extract_options! actions_to_remove = Array(options[:except]) actions_to_remove += ACTIONS - actions_to_keep.map { |a| a.to_sym } unless actions_to_keep.first == :all actions_to_remove.map! { |a| a.to_sym }.uniq! (instance_methods.map { |m| m.to_sym } & actions_to_remove).each do |action| undef_method action, "#{action}!" end end
ruby
def actions(*actions_to_keep) raise ArgumentError, 'Wrong number of arguments. You have to provide which actions you want to keep.' if actions_to_keep.empty? options = actions_to_keep.extract_options! actions_to_remove = Array(options[:except]) actions_to_remove += ACTIONS - actions_to_keep.map { |a| a.to_sym } unless actions_to_keep.first == :all actions_to_remove.map! { |a| a.to_sym }.uniq! (instance_methods.map { |m| m.to_sym } & actions_to_remove).each do |action| undef_method action, "#{action}!" end end
[ "def", "actions", "(", "*", "actions_to_keep", ")", "raise", "ArgumentError", ",", "'Wrong number of arguments. You have to provide which actions you want to keep.'", "if", "actions_to_keep", ".", "empty?", "options", "=", "actions_to_keep", ".", "extract_options!", "actions_to_remove", "=", "Array", "(", "options", "[", ":except", "]", ")", "actions_to_remove", "+=", "ACTIONS", "-", "actions_to_keep", ".", "map", "{", "|", "a", "|", "a", ".", "to_sym", "}", "unless", "actions_to_keep", ".", "first", "==", ":all", "actions_to_remove", ".", "map!", "{", "|", "a", "|", "a", ".", "to_sym", "}", ".", "uniq!", "(", "instance_methods", ".", "map", "{", "|", "m", "|", "m", ".", "to_sym", "}", "&", "actions_to_remove", ")", ".", "each", "do", "|", "action", "|", "undef_method", "action", ",", "\"#{action}!\"", "end", "end" ]
Defines wich actions will be inherited from the inherited controller. Syntax is borrowed from resource_controller. actions :index, :show, :edit actions :all, :except => :index
[ "Defines", "wich", "actions", "will", "be", "inherited", "from", "the", "inherited", "controller", ".", "Syntax", "is", "borrowed", "from", "resource_controller", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/class_methods.rb#L75-L85
train
activeadmin/inherited_resources
lib/inherited_resources/class_methods.rb
InheritedResources.ClassMethods.polymorphic_belongs_to
def polymorphic_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(polymorphic: true) belongs_to(*symbols, options, &block) end
ruby
def polymorphic_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(polymorphic: true) belongs_to(*symbols, options, &block) end
[ "def", "polymorphic_belongs_to", "(", "*", "symbols", ",", "&", "block", ")", "options", "=", "symbols", ".", "extract_options!", "options", ".", "merge!", "(", "polymorphic", ":", "true", ")", "belongs_to", "(", "symbols", ",", "options", ",", "block", ")", "end" ]
A quick method to declare polymorphic belongs to.
[ "A", "quick", "method", "to", "declare", "polymorphic", "belongs", "to", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/class_methods.rb#L229-L233
train
activeadmin/inherited_resources
lib/inherited_resources/class_methods.rb
InheritedResources.ClassMethods.singleton_belongs_to
def singleton_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(singleton: true) belongs_to(*symbols, options, &block) end
ruby
def singleton_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(singleton: true) belongs_to(*symbols, options, &block) end
[ "def", "singleton_belongs_to", "(", "*", "symbols", ",", "&", "block", ")", "options", "=", "symbols", ".", "extract_options!", "options", ".", "merge!", "(", "singleton", ":", "true", ")", "belongs_to", "(", "symbols", ",", "options", ",", "block", ")", "end" ]
A quick method to declare singleton belongs to.
[ "A", "quick", "method", "to", "declare", "singleton", "belongs", "to", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/class_methods.rb#L237-L241
train
activeadmin/inherited_resources
lib/inherited_resources/class_methods.rb
InheritedResources.ClassMethods.optional_belongs_to
def optional_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(optional: true) belongs_to(*symbols, options, &block) end
ruby
def optional_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(optional: true) belongs_to(*symbols, options, &block) end
[ "def", "optional_belongs_to", "(", "*", "symbols", ",", "&", "block", ")", "options", "=", "symbols", ".", "extract_options!", "options", ".", "merge!", "(", "optional", ":", "true", ")", "belongs_to", "(", "symbols", ",", "options", ",", "block", ")", "end" ]
A quick method to declare optional belongs to.
[ "A", "quick", "method", "to", "declare", "optional", "belongs", "to", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/class_methods.rb#L245-L249
train
activeadmin/inherited_resources
lib/inherited_resources/class_methods.rb
InheritedResources.ClassMethods.custom_actions
def custom_actions(options) self.resources_configuration[:self][:custom_actions] = options options.each do | resource_or_collection, actions | [*actions].each do | action | create_custom_action(resource_or_collection, action) end end create_resources_url_helpers! [*options[:resource]].each do | action | helper_method "#{action}_resource_path", "#{action}_resource_url" end [*options[:collection]].each do | action | helper_method "#{action}_resources_path", "#{action}_resources_url" end end
ruby
def custom_actions(options) self.resources_configuration[:self][:custom_actions] = options options.each do | resource_or_collection, actions | [*actions].each do | action | create_custom_action(resource_or_collection, action) end end create_resources_url_helpers! [*options[:resource]].each do | action | helper_method "#{action}_resource_path", "#{action}_resource_url" end [*options[:collection]].each do | action | helper_method "#{action}_resources_path", "#{action}_resources_url" end end
[ "def", "custom_actions", "(", "options", ")", "self", ".", "resources_configuration", "[", ":self", "]", "[", ":custom_actions", "]", "=", "options", "options", ".", "each", "do", "|", "resource_or_collection", ",", "actions", "|", "[", "actions", "]", ".", "each", "do", "|", "action", "|", "create_custom_action", "(", "resource_or_collection", ",", "action", ")", "end", "end", "create_resources_url_helpers!", "[", "options", "[", ":resource", "]", "]", ".", "each", "do", "|", "action", "|", "helper_method", "\"#{action}_resource_path\"", ",", "\"#{action}_resource_url\"", "end", "[", "options", "[", ":collection", "]", "]", ".", "each", "do", "|", "action", "|", "helper_method", "\"#{action}_resources_path\"", ",", "\"#{action}_resources_url\"", "end", "end" ]
Defines custom restful actions by resource or collection basis. custom_actions :resource => [:delete, :transit], :collection => :search == Options * <tt>:resource</tt> - Allows you to specify resource actions. custom_actions :resource => :delete This macro creates 'delete' method in controller and defines delete_resource_{path,url} helpers. The body of generated 'delete' method is same as 'show' method. So you can override it if need * <tt>:collection</tt> - Allows you to specify collection actions. custom_actions :collection => :search This macro creates 'search' method in controller and defines search_resources_{path,url} helpers. The body of generated 'search' method is same as 'index' method. So you can override it if need
[ "Defines", "custom", "restful", "actions", "by", "resource", "or", "collection", "basis", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/class_methods.rb#L269-L283
train
activeadmin/inherited_resources
lib/inherited_resources/class_methods.rb
InheritedResources.ClassMethods.initialize_resources_class_accessors!
def initialize_resources_class_accessors! #:nodoc: # First priority is the namespaced model, e.g. User::Group self.resource_class ||= begin namespaced_class = self.name.sub(/Controller$/, '').singularize namespaced_class.constantize rescue NameError nil end # Second priority is the top namespace model, e.g. EngineName::Article for EngineName::Admin::ArticlesController self.resource_class ||= begin namespaced_classes = self.name.sub(/Controller$/, '').split('::') namespaced_class = [namespaced_classes.first, namespaced_classes.last].join('::').singularize namespaced_class.constantize rescue NameError nil end # Third priority the camelcased c, i.e. UserGroup self.resource_class ||= begin camelcased_class = self.name.sub(/Controller$/, '').gsub('::', '').singularize camelcased_class.constantize rescue NameError nil end # Otherwise use the Group class, or fail self.resource_class ||= begin class_name = self.controller_name.classify class_name.constantize rescue NameError => e raise unless e.message.include?(class_name) nil end self.parents_symbols = self.parents_symbols.try(:dup) || [] # Initialize resources configuration hash self.resources_configuration = self.resources_configuration.try(:dup) || {} self.resources_configuration.each do |key, value| next unless value.is_a?(Hash) || value.is_a?(Array) self.resources_configuration[key] = value.dup end config = (self.resources_configuration[:self] ||= {}) config[:collection_name] = self.controller_name.to_sym config[:instance_name] = self.controller_name.singularize.to_sym config[:route_collection_name] = config[:collection_name] config[:route_instance_name] = config[:instance_name] # Deal with namespaced controllers namespaces = self.controller_path.split('/')[0..-2] # Remove namespace if its a mountable engine namespaces.delete_if do |namespace| begin "#{namespace}/engine".camelize.constantize.isolated? rescue StandardError, LoadError false end end config[:route_prefix] = namespaces.join('_') unless namespaces.empty? # Deal with default request parameters in namespaced controllers, e.g. # Forum::Thread#create will properly pick up the request parameter # which will be forum_thread, and not thread # Additionally make this work orthogonally with instance_name config[:request_name] = self.resource_class.to_s.underscore.gsub('/', '_') # Initialize polymorphic, singleton, scopes and belongs_to parameters polymorphic = self.resources_configuration[:polymorphic] || { symbols: [], optional: false } polymorphic[:symbols] = polymorphic[:symbols].dup self.resources_configuration[:polymorphic] = polymorphic end
ruby
def initialize_resources_class_accessors! #:nodoc: # First priority is the namespaced model, e.g. User::Group self.resource_class ||= begin namespaced_class = self.name.sub(/Controller$/, '').singularize namespaced_class.constantize rescue NameError nil end # Second priority is the top namespace model, e.g. EngineName::Article for EngineName::Admin::ArticlesController self.resource_class ||= begin namespaced_classes = self.name.sub(/Controller$/, '').split('::') namespaced_class = [namespaced_classes.first, namespaced_classes.last].join('::').singularize namespaced_class.constantize rescue NameError nil end # Third priority the camelcased c, i.e. UserGroup self.resource_class ||= begin camelcased_class = self.name.sub(/Controller$/, '').gsub('::', '').singularize camelcased_class.constantize rescue NameError nil end # Otherwise use the Group class, or fail self.resource_class ||= begin class_name = self.controller_name.classify class_name.constantize rescue NameError => e raise unless e.message.include?(class_name) nil end self.parents_symbols = self.parents_symbols.try(:dup) || [] # Initialize resources configuration hash self.resources_configuration = self.resources_configuration.try(:dup) || {} self.resources_configuration.each do |key, value| next unless value.is_a?(Hash) || value.is_a?(Array) self.resources_configuration[key] = value.dup end config = (self.resources_configuration[:self] ||= {}) config[:collection_name] = self.controller_name.to_sym config[:instance_name] = self.controller_name.singularize.to_sym config[:route_collection_name] = config[:collection_name] config[:route_instance_name] = config[:instance_name] # Deal with namespaced controllers namespaces = self.controller_path.split('/')[0..-2] # Remove namespace if its a mountable engine namespaces.delete_if do |namespace| begin "#{namespace}/engine".camelize.constantize.isolated? rescue StandardError, LoadError false end end config[:route_prefix] = namespaces.join('_') unless namespaces.empty? # Deal with default request parameters in namespaced controllers, e.g. # Forum::Thread#create will properly pick up the request parameter # which will be forum_thread, and not thread # Additionally make this work orthogonally with instance_name config[:request_name] = self.resource_class.to_s.underscore.gsub('/', '_') # Initialize polymorphic, singleton, scopes and belongs_to parameters polymorphic = self.resources_configuration[:polymorphic] || { symbols: [], optional: false } polymorphic[:symbols] = polymorphic[:symbols].dup self.resources_configuration[:polymorphic] = polymorphic end
[ "def", "initialize_resources_class_accessors!", "#:nodoc:", "# First priority is the namespaced model, e.g. User::Group", "self", ".", "resource_class", "||=", "begin", "namespaced_class", "=", "self", ".", "name", ".", "sub", "(", "/", "/", ",", "''", ")", ".", "singularize", "namespaced_class", ".", "constantize", "rescue", "NameError", "nil", "end", "# Second priority is the top namespace model, e.g. EngineName::Article for EngineName::Admin::ArticlesController", "self", ".", "resource_class", "||=", "begin", "namespaced_classes", "=", "self", ".", "name", ".", "sub", "(", "/", "/", ",", "''", ")", ".", "split", "(", "'::'", ")", "namespaced_class", "=", "[", "namespaced_classes", ".", "first", ",", "namespaced_classes", ".", "last", "]", ".", "join", "(", "'::'", ")", ".", "singularize", "namespaced_class", ".", "constantize", "rescue", "NameError", "nil", "end", "# Third priority the camelcased c, i.e. UserGroup", "self", ".", "resource_class", "||=", "begin", "camelcased_class", "=", "self", ".", "name", ".", "sub", "(", "/", "/", ",", "''", ")", ".", "gsub", "(", "'::'", ",", "''", ")", ".", "singularize", "camelcased_class", ".", "constantize", "rescue", "NameError", "nil", "end", "# Otherwise use the Group class, or fail", "self", ".", "resource_class", "||=", "begin", "class_name", "=", "self", ".", "controller_name", ".", "classify", "class_name", ".", "constantize", "rescue", "NameError", "=>", "e", "raise", "unless", "e", ".", "message", ".", "include?", "(", "class_name", ")", "nil", "end", "self", ".", "parents_symbols", "=", "self", ".", "parents_symbols", ".", "try", "(", ":dup", ")", "||", "[", "]", "# Initialize resources configuration hash", "self", ".", "resources_configuration", "=", "self", ".", "resources_configuration", ".", "try", "(", ":dup", ")", "||", "{", "}", "self", ".", "resources_configuration", ".", "each", "do", "|", "key", ",", "value", "|", "next", "unless", "value", ".", "is_a?", "(", "Hash", ")", "||", "value", ".", "is_a?", "(", "Array", ")", "self", ".", "resources_configuration", "[", "key", "]", "=", "value", ".", "dup", "end", "config", "=", "(", "self", ".", "resources_configuration", "[", ":self", "]", "||=", "{", "}", ")", "config", "[", ":collection_name", "]", "=", "self", ".", "controller_name", ".", "to_sym", "config", "[", ":instance_name", "]", "=", "self", ".", "controller_name", ".", "singularize", ".", "to_sym", "config", "[", ":route_collection_name", "]", "=", "config", "[", ":collection_name", "]", "config", "[", ":route_instance_name", "]", "=", "config", "[", ":instance_name", "]", "# Deal with namespaced controllers", "namespaces", "=", "self", ".", "controller_path", ".", "split", "(", "'/'", ")", "[", "0", "..", "-", "2", "]", "# Remove namespace if its a mountable engine", "namespaces", ".", "delete_if", "do", "|", "namespace", "|", "begin", "\"#{namespace}/engine\"", ".", "camelize", ".", "constantize", ".", "isolated?", "rescue", "StandardError", ",", "LoadError", "false", "end", "end", "config", "[", ":route_prefix", "]", "=", "namespaces", ".", "join", "(", "'_'", ")", "unless", "namespaces", ".", "empty?", "# Deal with default request parameters in namespaced controllers, e.g.", "# Forum::Thread#create will properly pick up the request parameter", "# which will be forum_thread, and not thread", "# Additionally make this work orthogonally with instance_name", "config", "[", ":request_name", "]", "=", "self", ".", "resource_class", ".", "to_s", ".", "underscore", ".", "gsub", "(", "'/'", ",", "'_'", ")", "# Initialize polymorphic, singleton, scopes and belongs_to parameters", "polymorphic", "=", "self", ".", "resources_configuration", "[", ":polymorphic", "]", "||", "{", "symbols", ":", "[", "]", ",", "optional", ":", "false", "}", "polymorphic", "[", ":symbols", "]", "=", "polymorphic", "[", ":symbols", "]", ".", "dup", "self", ".", "resources_configuration", "[", ":polymorphic", "]", "=", "polymorphic", "end" ]
Initialize resources class accessors and set their default values.
[ "Initialize", "resources", "class", "accessors", "and", "set", "their", "default", "values", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/class_methods.rb#L319-L394
train
activeadmin/inherited_resources
lib/inherited_resources/polymorphic_helpers.rb
InheritedResources.PolymorphicHelpers.symbols_for_association_chain
def symbols_for_association_chain #:nodoc: polymorphic_config = resources_configuration[:polymorphic] parents_symbols.map do |symbol| if symbol == :polymorphic params_keys = params.keys keys = polymorphic_config[:symbols].map do |poly| params_keys.include?(resources_configuration[poly][:param].to_s) ? poly : nil end.compact if keys.empty? raise ScriptError, "Could not find param for polymorphic association. The request " << "parameters are #{params.keys.inspect} and the polymorphic " << "associations are #{polymorphic_config[:symbols].inspect}." unless polymorphic_config[:optional] nil else @parent_type = keys[-1].to_sym @parent_types = keys.map(&:to_sym) end else symbol end end.flatten.compact end
ruby
def symbols_for_association_chain #:nodoc: polymorphic_config = resources_configuration[:polymorphic] parents_symbols.map do |symbol| if symbol == :polymorphic params_keys = params.keys keys = polymorphic_config[:symbols].map do |poly| params_keys.include?(resources_configuration[poly][:param].to_s) ? poly : nil end.compact if keys.empty? raise ScriptError, "Could not find param for polymorphic association. The request " << "parameters are #{params.keys.inspect} and the polymorphic " << "associations are #{polymorphic_config[:symbols].inspect}." unless polymorphic_config[:optional] nil else @parent_type = keys[-1].to_sym @parent_types = keys.map(&:to_sym) end else symbol end end.flatten.compact end
[ "def", "symbols_for_association_chain", "#:nodoc:", "polymorphic_config", "=", "resources_configuration", "[", ":polymorphic", "]", "parents_symbols", ".", "map", "do", "|", "symbol", "|", "if", "symbol", "==", ":polymorphic", "params_keys", "=", "params", ".", "keys", "keys", "=", "polymorphic_config", "[", ":symbols", "]", ".", "map", "do", "|", "poly", "|", "params_keys", ".", "include?", "(", "resources_configuration", "[", "poly", "]", "[", ":param", "]", ".", "to_s", ")", "?", "poly", ":", "nil", "end", ".", "compact", "if", "keys", ".", "empty?", "raise", "ScriptError", ",", "\"Could not find param for polymorphic association. The request \"", "<<", "\"parameters are #{params.keys.inspect} and the polymorphic \"", "<<", "\"associations are #{polymorphic_config[:symbols].inspect}.\"", "unless", "polymorphic_config", "[", ":optional", "]", "nil", "else", "@parent_type", "=", "keys", "[", "-", "1", "]", ".", "to_sym", "@parent_types", "=", "keys", ".", "map", "(", ":to_sym", ")", "end", "else", "symbol", "end", "end", ".", "flatten", ".", "compact", "end" ]
Maps parents_symbols to build association chain. If the parents_symbols find :polymorphic, it goes through the params keys to see which polymorphic parent matches the given params. When optional is given, it does not raise errors if the polymorphic params are missing.
[ "Maps", "parents_symbols", "to", "build", "association", "chain", "." ]
2ba6982ddd6a56e7ef9ed7396473e5500ad77126
https://github.com/activeadmin/inherited_resources/blob/2ba6982ddd6a56e7ef9ed7396473e5500ad77126/lib/inherited_resources/polymorphic_helpers.rb#L148-L172
train
unsplash/unsplash_rb
lib/unsplash/connection.rb
Unsplash.Connection.authorization_url
def authorization_url(requested_scopes = ["public"]) @oauth.auth_code.authorize_url(redirect_uri: Unsplash.configuration.application_redirect_uri, scope: requested_scopes.join(" ")) end
ruby
def authorization_url(requested_scopes = ["public"]) @oauth.auth_code.authorize_url(redirect_uri: Unsplash.configuration.application_redirect_uri, scope: requested_scopes.join(" ")) end
[ "def", "authorization_url", "(", "requested_scopes", "=", "[", "\"public\"", "]", ")", "@oauth", ".", "auth_code", ".", "authorize_url", "(", "redirect_uri", ":", "Unsplash", ".", "configuration", ".", "application_redirect_uri", ",", "scope", ":", "requested_scopes", ".", "join", "(", "\" \"", ")", ")", "end" ]
Create a Connection object. @param version [String] The Unsplash API version to use. @param api_base_uri [String] Base URI at which to make API calls. @param oauth_base_uri [String] Base URI for OAuth requests. Get OAuth URL for user authentication and authorization. @param requested_scopes [Array] An array of permission scopes being requested. @return [String] The authorization URL.
[ "Create", "a", "Connection", "object", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/connection.rb#L39-L42
train
unsplash/unsplash_rb
lib/unsplash/client.rb
Unsplash.Client.reload!
def reload! if links && links["self"] attrs = JSON.parse(connection.get(links["self"]).body) @attributes = OpenStruct.new(attrs) self else raise Unsplash::Error.new "Missing self link for #{self.class} with ID #{self.id}" end end
ruby
def reload! if links && links["self"] attrs = JSON.parse(connection.get(links["self"]).body) @attributes = OpenStruct.new(attrs) self else raise Unsplash::Error.new "Missing self link for #{self.class} with ID #{self.id}" end end
[ "def", "reload!", "if", "links", "&&", "links", "[", "\"self\"", "]", "attrs", "=", "JSON", ".", "parse", "(", "connection", ".", "get", "(", "links", "[", "\"self\"", "]", ")", ".", "body", ")", "@attributes", "=", "OpenStruct", ".", "new", "(", "attrs", ")", "self", "else", "raise", "Unsplash", "::", "Error", ".", "new", "\"Missing self link for #{self.class} with ID #{self.id}\"", "end", "end" ]
Build an Unsplash object with the given attributes. @param attrs [Hash] (Re)load full object details from Unsplash. @return [Unspash::Client] Itself, with full details reloaded.
[ "Build", "an", "Unsplash", "object", "with", "the", "given", "attributes", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/client.rb#L14-L22
train
unsplash/unsplash_rb
lib/unsplash/user.rb
Unsplash.User.photos
def photos(page = 1, per_page = 10) params = { page: page, per_page: per_page } list = JSON.parse(connection.get("/users/#{username}/photos", params).body) list.map do |photo| Unsplash::Photo.new photo.to_hash end end
ruby
def photos(page = 1, per_page = 10) params = { page: page, per_page: per_page } list = JSON.parse(connection.get("/users/#{username}/photos", params).body) list.map do |photo| Unsplash::Photo.new photo.to_hash end end
[ "def", "photos", "(", "page", "=", "1", ",", "per_page", "=", "10", ")", "params", "=", "{", "page", ":", "page", ",", "per_page", ":", "per_page", "}", "list", "=", "JSON", ".", "parse", "(", "connection", ".", "get", "(", "\"/users/#{username}/photos\"", ",", "params", ")", ".", "body", ")", "list", ".", "map", "do", "|", "photo", "|", "Unsplash", "::", "Photo", ".", "new", "photo", ".", "to_hash", "end", "end" ]
Get a list of photos uploaded by the user. @param page [Integer] Which page of results to return. @param per_page [Integer] The number of results per page. @return [Array] a list of +Unsplash::Photo+ objects.
[ "Get", "a", "list", "of", "photos", "uploaded", "by", "the", "user", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/user.rb#L48-L58
train
unsplash/unsplash_rb
lib/unsplash/user.rb
Unsplash.User.collections
def collections(page = 1, per_page = 10) params = { page: page, per_page: per_page } list = JSON.parse(connection.get("/users/#{username}/collections", params).body) list.map do |collection| Unsplash::Collection.new collection.to_hash end end
ruby
def collections(page = 1, per_page = 10) params = { page: page, per_page: per_page } list = JSON.parse(connection.get("/users/#{username}/collections", params).body) list.map do |collection| Unsplash::Collection.new collection.to_hash end end
[ "def", "collections", "(", "page", "=", "1", ",", "per_page", "=", "10", ")", "params", "=", "{", "page", ":", "page", ",", "per_page", ":", "per_page", "}", "list", "=", "JSON", ".", "parse", "(", "connection", ".", "get", "(", "\"/users/#{username}/collections\"", ",", "params", ")", ".", "body", ")", "list", ".", "map", "do", "|", "collection", "|", "Unsplash", "::", "Collection", ".", "new", "collection", ".", "to_hash", "end", "end" ]
Get a list of collections created by the user. @param page [Integer] Which page of results to return. @param per_page [Integer] The number of results per page. (default: 10, maximum: 30) @return [Array] a list of +Unsplash::Collection+ objects.
[ "Get", "a", "list", "of", "collections", "created", "by", "the", "user", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/user.rb#L80-L90
train
unsplash/unsplash_rb
lib/unsplash/collection.rb
Unsplash.Collection.update
def update(title: nil, description: nil, private: nil) params = { title: title, description: description, private: private }.select { |k,v| v } updated = JSON.parse(connection.put("/collections/#{id}", params).body) self.title = updated["title"] self.description = updated["description"] self end
ruby
def update(title: nil, description: nil, private: nil) params = { title: title, description: description, private: private }.select { |k,v| v } updated = JSON.parse(connection.put("/collections/#{id}", params).body) self.title = updated["title"] self.description = updated["description"] self end
[ "def", "update", "(", "title", ":", "nil", ",", "description", ":", "nil", ",", "private", ":", "nil", ")", "params", "=", "{", "title", ":", "title", ",", "description", ":", "description", ",", "private", ":", "private", "}", ".", "select", "{", "|", "k", ",", "v", "|", "v", "}", "updated", "=", "JSON", ".", "parse", "(", "connection", ".", "put", "(", "\"/collections/#{id}\"", ",", "params", ")", ".", "body", ")", "self", ".", "title", "=", "updated", "[", "\"title\"", "]", "self", ".", "description", "=", "updated", "[", "\"description\"", "]", "self", "end" ]
Update the collection's attributes. @param title [String] The title of the collection. @param description [String] The collection's description. (optional) @param private [Boolean] Whether to make the collection private. (optional)
[ "Update", "the", "collection", "s", "attributes", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/collection.rb#L81-L91
train
unsplash/unsplash_rb
lib/unsplash/collection.rb
Unsplash.Collection.add
def add(photo) response = JSON.parse(connection.post("/collections/#{id}/add", { photo_id: photo.id }).body) { photo_id: response["photo"]["id"], collection_id: response["collection"]["id"], user_id: response["user"]["id"], created_at: response["created_at"] } end
ruby
def add(photo) response = JSON.parse(connection.post("/collections/#{id}/add", { photo_id: photo.id }).body) { photo_id: response["photo"]["id"], collection_id: response["collection"]["id"], user_id: response["user"]["id"], created_at: response["created_at"] } end
[ "def", "add", "(", "photo", ")", "response", "=", "JSON", ".", "parse", "(", "connection", ".", "post", "(", "\"/collections/#{id}/add\"", ",", "{", "photo_id", ":", "photo", ".", "id", "}", ")", ".", "body", ")", "{", "photo_id", ":", "response", "[", "\"photo\"", "]", "[", "\"id\"", "]", ",", "collection_id", ":", "response", "[", "\"collection\"", "]", "[", "\"id\"", "]", ",", "user_id", ":", "response", "[", "\"user\"", "]", "[", "\"id\"", "]", ",", "created_at", ":", "response", "[", "\"created_at\"", "]", "}", "end" ]
Add a photo to the collection. If the photo is already in the collection, this action has no effect. @param [Unsplash::Photo] The photo to add. @return [Hash] Collected photo metadata.
[ "Add", "a", "photo", "to", "the", "collection", ".", "If", "the", "photo", "is", "already", "in", "the", "collection", "this", "action", "has", "no", "effect", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/collection.rb#L118-L126
train
unsplash/unsplash_rb
lib/unsplash/collection.rb
Unsplash.Collection.remove
def remove(photo) response = connection.delete("/collections/#{id}/remove", photo_id: photo.id) (200..299).include?(response.status) end
ruby
def remove(photo) response = connection.delete("/collections/#{id}/remove", photo_id: photo.id) (200..299).include?(response.status) end
[ "def", "remove", "(", "photo", ")", "response", "=", "connection", ".", "delete", "(", "\"/collections/#{id}/remove\"", ",", "photo_id", ":", "photo", ".", "id", ")", "(", "200", "..", "299", ")", ".", "include?", "(", "response", ".", "status", ")", "end" ]
Remove a photo from the collection. If the photo is not in the collection, this action has no effect. @param [Unsplash::Photo] The photo to remove. @return [Boolean] +true+ on success.
[ "Remove", "a", "photo", "from", "the", "collection", ".", "If", "the", "photo", "is", "not", "in", "the", "collection", "this", "action", "has", "no", "effect", "." ]
d2b3f1721616941671621fca332b183d9b6053b4
https://github.com/unsplash/unsplash_rb/blob/d2b3f1721616941671621fca332b183d9b6053b4/lib/unsplash/collection.rb#L132-L135
train
floraison/fugit
lib/fugit/duration.rb
Fugit.Duration.drop_seconds
def drop_seconds h = @h.dup h.delete(:sec) h[:min] = 0 if h.empty? self.class.allocate.init(nil, { literal: true }, h) end
ruby
def drop_seconds h = @h.dup h.delete(:sec) h[:min] = 0 if h.empty? self.class.allocate.init(nil, { literal: true }, h) end
[ "def", "drop_seconds", "h", "=", "@h", ".", "dup", "h", ".", "delete", "(", ":sec", ")", "h", "[", ":min", "]", "=", "0", "if", "h", ".", "empty?", "self", ".", "class", ".", "allocate", ".", "init", "(", "nil", ",", "{", "literal", ":", "true", "}", ",", "h", ")", "end" ]
Returns a copy of this duration, omitting its seconds.
[ "Returns", "a", "copy", "of", "this", "duration", "omitting", "its", "seconds", "." ]
f9f5e48a06e615b1e29f8ec176c40bbd2cfaf151
https://github.com/floraison/fugit/blob/f9f5e48a06e615b1e29f8ec176c40bbd2cfaf151/lib/fugit/duration.rb#L297-L304
train
huacnlee/rucaptcha
lib/rucaptcha/controller_helpers.rb
RuCaptcha.ControllerHelpers.rucaptcha_sesion_key_key
def rucaptcha_sesion_key_key session_id = session.respond_to?(:id) ? session.id : session[:session_id] warning_when_session_invalid if session_id.blank? ['rucaptcha-session', session_id].join(':') end
ruby
def rucaptcha_sesion_key_key session_id = session.respond_to?(:id) ? session.id : session[:session_id] warning_when_session_invalid if session_id.blank? ['rucaptcha-session', session_id].join(':') end
[ "def", "rucaptcha_sesion_key_key", "session_id", "=", "session", ".", "respond_to?", "(", ":id", ")", "?", "session", ".", "id", ":", "session", "[", ":session_id", "]", "warning_when_session_invalid", "if", "session_id", ".", "blank?", "[", "'rucaptcha-session'", ",", "session_id", "]", ".", "join", "(", "':'", ")", "end" ]
session key of rucaptcha
[ "session", "key", "of", "rucaptcha" ]
b7074ed9fd84e9768e91b39555ea037ffd327032
https://github.com/huacnlee/rucaptcha/blob/b7074ed9fd84e9768e91b39555ea037ffd327032/lib/rucaptcha/controller_helpers.rb#L10-L14
train
huacnlee/rucaptcha
lib/rucaptcha/controller_helpers.rb
RuCaptcha.ControllerHelpers.generate_rucaptcha
def generate_rucaptcha res = RuCaptcha.generate() session_val = { code: res[0], time: Time.now.to_i } RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in) res[1] end
ruby
def generate_rucaptcha res = RuCaptcha.generate() session_val = { code: res[0], time: Time.now.to_i } RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in) res[1] end
[ "def", "generate_rucaptcha", "res", "=", "RuCaptcha", ".", "generate", "(", ")", "session_val", "=", "{", "code", ":", "res", "[", "0", "]", ",", "time", ":", "Time", ".", "now", ".", "to_i", "}", "RuCaptcha", ".", "cache", ".", "write", "(", "rucaptcha_sesion_key_key", ",", "session_val", ",", "expires_in", ":", "RuCaptcha", ".", "config", ".", "expires_in", ")", "res", "[", "1", "]", "end" ]
Generate a new Captcha
[ "Generate", "a", "new", "Captcha" ]
b7074ed9fd84e9768e91b39555ea037ffd327032
https://github.com/huacnlee/rucaptcha/blob/b7074ed9fd84e9768e91b39555ea037ffd327032/lib/rucaptcha/controller_helpers.rb#L17-L25
train
huacnlee/rucaptcha
lib/rucaptcha/controller_helpers.rb
RuCaptcha.ControllerHelpers.verify_rucaptcha?
def verify_rucaptcha?(resource = nil, opts = {}) opts ||= {} store_info = RuCaptcha.cache.read(rucaptcha_sesion_key_key) # make sure move used key RuCaptcha.cache.delete(rucaptcha_sesion_key_key) unless opts[:keep_session] # Make sure session exist if store_info.blank? return add_rucaptcha_validation_error end # Make sure not expire if (Time.now.to_i - store_info[:time]) > RuCaptcha.config.expires_in return add_rucaptcha_validation_error end # Make sure parama have captcha captcha = (opts[:captcha] || params[:_rucaptcha] || '').downcase.strip if captcha.blank? return add_rucaptcha_validation_error end if captcha != store_info[:code] return add_rucaptcha_validation_error end true end
ruby
def verify_rucaptcha?(resource = nil, opts = {}) opts ||= {} store_info = RuCaptcha.cache.read(rucaptcha_sesion_key_key) # make sure move used key RuCaptcha.cache.delete(rucaptcha_sesion_key_key) unless opts[:keep_session] # Make sure session exist if store_info.blank? return add_rucaptcha_validation_error end # Make sure not expire if (Time.now.to_i - store_info[:time]) > RuCaptcha.config.expires_in return add_rucaptcha_validation_error end # Make sure parama have captcha captcha = (opts[:captcha] || params[:_rucaptcha] || '').downcase.strip if captcha.blank? return add_rucaptcha_validation_error end if captcha != store_info[:code] return add_rucaptcha_validation_error end true end
[ "def", "verify_rucaptcha?", "(", "resource", "=", "nil", ",", "opts", "=", "{", "}", ")", "opts", "||=", "{", "}", "store_info", "=", "RuCaptcha", ".", "cache", ".", "read", "(", "rucaptcha_sesion_key_key", ")", "# make sure move used key", "RuCaptcha", ".", "cache", ".", "delete", "(", "rucaptcha_sesion_key_key", ")", "unless", "opts", "[", ":keep_session", "]", "# Make sure session exist", "if", "store_info", ".", "blank?", "return", "add_rucaptcha_validation_error", "end", "# Make sure not expire", "if", "(", "Time", ".", "now", ".", "to_i", "-", "store_info", "[", ":time", "]", ")", ">", "RuCaptcha", ".", "config", ".", "expires_in", "return", "add_rucaptcha_validation_error", "end", "# Make sure parama have captcha", "captcha", "=", "(", "opts", "[", ":captcha", "]", "||", "params", "[", ":_rucaptcha", "]", "||", "''", ")", ".", "downcase", ".", "strip", "if", "captcha", ".", "blank?", "return", "add_rucaptcha_validation_error", "end", "if", "captcha", "!=", "store_info", "[", ":code", "]", "return", "add_rucaptcha_validation_error", "end", "true", "end" ]
Verify captcha code params: resource - [optional] a ActiveModel object, if given will add validation error message to object. :keep_session - if true, RuCaptcha will not delete the captcha code session. :captcha - if given, the value of it will be used to verify the captcha, if do not give or blank, the value of params[:_rucaptcha] will be used to verify the captcha exmaples: verify_rucaptcha? verify_rucaptcha?(user, keep_session: true) verify_rucaptcha?(nil, keep_session: true) verify_rucaptcha?(nil, captcha: params[:user][:captcha])
[ "Verify", "captcha", "code" ]
b7074ed9fd84e9768e91b39555ea037ffd327032
https://github.com/huacnlee/rucaptcha/blob/b7074ed9fd84e9768e91b39555ea037ffd327032/lib/rucaptcha/controller_helpers.rb#L42-L70
train
oesmith/puffing-billy
lib/billy/ssl/authority.rb
Billy.Authority.generate
def generate cert = OpenSSL::X509::Certificate.new configure(cert) add_extensions(cert) cert.sign(key, OpenSSL::Digest::SHA256.new) end
ruby
def generate cert = OpenSSL::X509::Certificate.new configure(cert) add_extensions(cert) cert.sign(key, OpenSSL::Digest::SHA256.new) end
[ "def", "generate", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "configure", "(", "cert", ")", "add_extensions", "(", "cert", ")", "cert", ".", "sign", "(", "key", ",", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", ")", "end" ]
Generate a fresh new certificate for the configured domain.
[ "Generate", "a", "fresh", "new", "certificate", "for", "the", "configured", "domain", "." ]
e1a2e2a16fe1ed0a50a20bc01bd181628c6a57e2
https://github.com/oesmith/puffing-billy/blob/e1a2e2a16fe1ed0a50a20bc01bd181628c6a57e2/lib/billy/ssl/authority.rb#L68-L73
train
oesmith/puffing-billy
lib/billy/ssl/certificate_chain.rb
Billy.CertificateChain.file
def file contents = certificates.map { |cert| cert.to_pem }.join write_file("chain-#{domain}.pem", contents) end
ruby
def file contents = certificates.map { |cert| cert.to_pem }.join write_file("chain-#{domain}.pem", contents) end
[ "def", "file", "contents", "=", "certificates", ".", "map", "{", "|", "cert", "|", "cert", ".", "to_pem", "}", ".", "join", "write_file", "(", "\"chain-#{domain}.pem\"", ",", "contents", ")", "end" ]
Just pass all certificates into the new instance. We use the variadic argument feature here to ease the usage and improve the readability. Example: certs_chain_file = Billy::CertificateChain.new('localhost', cert1, cert2, ..).file Write out the certificates chain file and pass the path back. This will produce a temporary file which will be remove after the current process terminates.
[ "Just", "pass", "all", "certificates", "into", "the", "new", "instance", ".", "We", "use", "the", "variadic", "argument", "feature", "here", "to", "ease", "the", "usage", "and", "improve", "the", "readability", "." ]
e1a2e2a16fe1ed0a50a20bc01bd181628c6a57e2
https://github.com/oesmith/puffing-billy/blob/e1a2e2a16fe1ed0a50a20bc01bd181628c6a57e2/lib/billy/ssl/certificate_chain.rb#L36-L39
train
zendesk/active_record_shards
lib/active_record_shards/connection_switcher-4-0.rb
ActiveRecordShards.ConnectionSwitcher.connection_pool_name
def connection_pool_name # :nodoc: name = current_shard_selection.shard_name(self) if configurations[name].nil? && on_slave? current_shard_selection.shard_name(self, false) else name end end
ruby
def connection_pool_name # :nodoc: name = current_shard_selection.shard_name(self) if configurations[name].nil? && on_slave? current_shard_selection.shard_name(self, false) else name end end
[ "def", "connection_pool_name", "# :nodoc:", "name", "=", "current_shard_selection", ".", "shard_name", "(", "self", ")", "if", "configurations", "[", "name", "]", ".", "nil?", "&&", "on_slave?", "current_shard_selection", ".", "shard_name", "(", "self", ",", "false", ")", "else", "name", "end", "end" ]
Name of the connection pool. Used by ConnectionHandler to retrieve the current connection pool.
[ "Name", "of", "the", "connection", "pool", ".", "Used", "by", "ConnectionHandler", "to", "retrieve", "the", "current", "connection", "pool", "." ]
a2a4daf8b1533e3b6de8447da759dca60a28e4e8
https://github.com/zendesk/active_record_shards/blob/a2a4daf8b1533e3b6de8447da759dca60a28e4e8/lib/active_record_shards/connection_switcher-4-0.rb#L4-L12
train
jimweirich/builder
lib/builder/xmlmarkup.rb
Builder.XmlMarkup.declare!
def declare!(inst, *args, &block) _indent @target << "<!#{inst}" args.each do |arg| case arg when ::String @target << %{ "#{arg}"} # " WART when ::Symbol @target << " #{arg}" end end if ::Kernel::block_given? @target << " [" _newline _nested_structures(block) @target << "]" end @target << ">" _newline end
ruby
def declare!(inst, *args, &block) _indent @target << "<!#{inst}" args.each do |arg| case arg when ::String @target << %{ "#{arg}"} # " WART when ::Symbol @target << " #{arg}" end end if ::Kernel::block_given? @target << " [" _newline _nested_structures(block) @target << "]" end @target << ">" _newline end
[ "def", "declare!", "(", "inst", ",", "*", "args", ",", "&", "block", ")", "_indent", "@target", "<<", "\"<!#{inst}\"", "args", ".", "each", "do", "|", "arg", "|", "case", "arg", "when", "::", "String", "@target", "<<", "%{ \"#{arg}\"}", "# \" WART", "when", "::", "Symbol", "@target", "<<", "\" #{arg}\"", "end", "end", "if", "::", "Kernel", "::", "block_given?", "@target", "<<", "\" [\"", "_newline", "_nested_structures", "(", "block", ")", "@target", "<<", "\"]\"", "end", "@target", "<<", "\">\"", "_newline", "end" ]
Insert an XML declaration into the XML markup. For example: xml.declare! :ELEMENT, :blah, "yada" # => <!ELEMENT blah "yada">
[ "Insert", "an", "XML", "declaration", "into", "the", "XML", "markup", "." ]
c80100f8205b2e918dbff605682b01ab0fabb866
https://github.com/jimweirich/builder/blob/c80100f8205b2e918dbff605682b01ab0fabb866/lib/builder/xmlmarkup.rb#L214-L233
train
jimweirich/builder
lib/builder/xmlmarkup.rb
Builder.XmlMarkup.instruct!
def instruct!(directive_tag=:xml, attrs={}) _ensure_no_block ::Kernel::block_given? if directive_tag == :xml a = { :version=>"1.0", :encoding=>"UTF-8" } attrs = a.merge attrs @encoding = attrs[:encoding].downcase end _special( "<?#{directive_tag}", "?>", nil, attrs, [:version, :encoding, :standalone]) end
ruby
def instruct!(directive_tag=:xml, attrs={}) _ensure_no_block ::Kernel::block_given? if directive_tag == :xml a = { :version=>"1.0", :encoding=>"UTF-8" } attrs = a.merge attrs @encoding = attrs[:encoding].downcase end _special( "<?#{directive_tag}", "?>", nil, attrs, [:version, :encoding, :standalone]) end
[ "def", "instruct!", "(", "directive_tag", "=", ":xml", ",", "attrs", "=", "{", "}", ")", "_ensure_no_block", "::", "Kernel", "::", "block_given?", "if", "directive_tag", "==", ":xml", "a", "=", "{", ":version", "=>", "\"1.0\"", ",", ":encoding", "=>", "\"UTF-8\"", "}", "attrs", "=", "a", ".", "merge", "attrs", "@encoding", "=", "attrs", "[", ":encoding", "]", ".", "downcase", "end", "_special", "(", "\"<?#{directive_tag}\"", ",", "\"?>\"", ",", "nil", ",", "attrs", ",", "[", ":version", ",", ":encoding", ",", ":standalone", "]", ")", "end" ]
Insert a processing instruction into the XML markup. E.g. For example: xml.instruct! #=> <?xml version="1.0" encoding="UTF-8"?> xml.instruct! :aaa, :bbb=>"ccc" #=> <?aaa bbb="ccc"?> Note: If the encoding is setup to "UTF-8" and the value of $KCODE is "UTF8", then builder will emit UTF-8 encoded strings rather than the entity encoding normally used.
[ "Insert", "a", "processing", "instruction", "into", "the", "XML", "markup", ".", "E", ".", "g", "." ]
c80100f8205b2e918dbff605682b01ab0fabb866
https://github.com/jimweirich/builder/blob/c80100f8205b2e918dbff605682b01ab0fabb866/lib/builder/xmlmarkup.rb#L247-L260
train
jimweirich/builder
lib/builder/xmlmarkup.rb
Builder.XmlMarkup._special
def _special(open, close, data=nil, attrs=nil, order=[]) _indent @target << open @target << data if data _insert_attributes(attrs, order) if attrs @target << close _newline end
ruby
def _special(open, close, data=nil, attrs=nil, order=[]) _indent @target << open @target << data if data _insert_attributes(attrs, order) if attrs @target << close _newline end
[ "def", "_special", "(", "open", ",", "close", ",", "data", "=", "nil", ",", "attrs", "=", "nil", ",", "order", "=", "[", "]", ")", "_indent", "@target", "<<", "open", "@target", "<<", "data", "if", "data", "_insert_attributes", "(", "attrs", ",", "order", ")", "if", "attrs", "@target", "<<", "close", "_newline", "end" ]
Insert special instruction.
[ "Insert", "special", "instruction", "." ]
c80100f8205b2e918dbff605682b01ab0fabb866
https://github.com/jimweirich/builder/blob/c80100f8205b2e918dbff605682b01ab0fabb866/lib/builder/xmlmarkup.rb#L285-L292
train
jimweirich/builder
lib/builder/xmlbase.rb
Builder.XmlBase.method_missing
def method_missing(sym, *args, &block) cache_method_call(sym) if ::Builder::XmlBase.cache_method_calls tag!(sym, *args, &block) end
ruby
def method_missing(sym, *args, &block) cache_method_call(sym) if ::Builder::XmlBase.cache_method_calls tag!(sym, *args, &block) end
[ "def", "method_missing", "(", "sym", ",", "*", "args", ",", "&", "block", ")", "cache_method_call", "(", "sym", ")", "if", "::", "Builder", "::", "XmlBase", ".", "cache_method_calls", "tag!", "(", "sym", ",", "args", ",", "block", ")", "end" ]
Create XML markup based on the name of the method. This method is never invoked directly, but is called for each markup method in the markup block that isn't cached.
[ "Create", "XML", "markup", "based", "on", "the", "name", "of", "the", "method", ".", "This", "method", "is", "never", "invoked", "directly", "but", "is", "called", "for", "each", "markup", "method", "in", "the", "markup", "block", "that", "isn", "t", "cached", "." ]
c80100f8205b2e918dbff605682b01ab0fabb866
https://github.com/jimweirich/builder/blob/c80100f8205b2e918dbff605682b01ab0fabb866/lib/builder/xmlbase.rb#L91-L94
train
jimweirich/builder
lib/builder/xmlbase.rb
Builder.XmlBase.cache_method_call
def cache_method_call(sym) class << self; self; end.class_eval do unless method_defined?(sym) define_method(sym) do |*args, &block| tag!(sym, *args, &block) end end end end
ruby
def cache_method_call(sym) class << self; self; end.class_eval do unless method_defined?(sym) define_method(sym) do |*args, &block| tag!(sym, *args, &block) end end end end
[ "def", "cache_method_call", "(", "sym", ")", "class", "<<", "self", ";", "self", ";", "end", ".", "class_eval", "do", "unless", "method_defined?", "(", "sym", ")", "define_method", "(", "sym", ")", "do", "|", "*", "args", ",", "&", "block", "|", "tag!", "(", "sym", ",", "args", ",", "block", ")", "end", "end", "end", "end" ]
If XmlBase.cache_method_calls = true, we dynamicly create the method missed as an instance method on the XMLBase object. Because XML documents are usually very repetative in nature, the next node will be handled by the new method instead of method_missing. As method_missing is very slow, this speeds up document generation significantly.
[ "If", "XmlBase", ".", "cache_method_calls", "=", "true", "we", "dynamicly", "create", "the", "method", "missed", "as", "an", "instance", "method", "on", "the", "XMLBase", "object", ".", "Because", "XML", "documents", "are", "usually", "very", "repetative", "in", "nature", "the", "next", "node", "will", "be", "handled", "by", "the", "new", "method", "instead", "of", "method_missing", ".", "As", "method_missing", "is", "very", "slow", "this", "speeds", "up", "document", "generation", "significantly", "." ]
c80100f8205b2e918dbff605682b01ab0fabb866
https://github.com/jimweirich/builder/blob/c80100f8205b2e918dbff605682b01ab0fabb866/lib/builder/xmlbase.rb#L186-L194
train
senny/sablon
lib/sablon/template.rb
Sablon.Template.render_to_file
def render_to_file(output_path, context, properties = {}) File.open(output_path, 'wb') do |f| f.write render_to_string(context, properties) end end
ruby
def render_to_file(output_path, context, properties = {}) File.open(output_path, 'wb') do |f| f.write render_to_string(context, properties) end end
[ "def", "render_to_file", "(", "output_path", ",", "context", ",", "properties", "=", "{", "}", ")", "File", ".", "open", "(", "output_path", ",", "'wb'", ")", "do", "|", "f", "|", "f", ".", "write", "render_to_string", "(", "context", ",", "properties", ")", "end", "end" ]
Same as +render_to_string+ but writes the processed template to +output_path+.
[ "Same", "as", "+", "render_to_string", "+", "but", "writes", "the", "processed", "template", "to", "+", "output_path", "+", "." ]
c43be5847593a3ecaf40c2b6138e549e0446c7f8
https://github.com/senny/sablon/blob/c43be5847593a3ecaf40c2b6138e549e0446c7f8/lib/sablon/template.rb#L41-L45
train
senny/sablon
lib/sablon/configuration/configuration.rb
Sablon.Configuration.register_html_tag
def register_html_tag(tag_name, type = :inline, **options) tag = HTMLTag.new(tag_name, type, **options) @permitted_html_tags[tag.name] = tag end
ruby
def register_html_tag(tag_name, type = :inline, **options) tag = HTMLTag.new(tag_name, type, **options) @permitted_html_tags[tag.name] = tag end
[ "def", "register_html_tag", "(", "tag_name", ",", "type", "=", ":inline", ",", "**", "options", ")", "tag", "=", "HTMLTag", ".", "new", "(", "tag_name", ",", "type", ",", "**", "options", ")", "@permitted_html_tags", "[", "tag", ".", "name", "]", "=", "tag", "end" ]
Adds a new tag to the permitted tags hash or replaces an existing one
[ "Adds", "a", "new", "tag", "to", "the", "permitted", "tags", "hash", "or", "replaces", "an", "existing", "one" ]
c43be5847593a3ecaf40c2b6138e549e0446c7f8
https://github.com/senny/sablon/blob/c43be5847593a3ecaf40c2b6138e549e0446c7f8/lib/sablon/configuration/configuration.rb#L17-L20
train
celluloid/celluloid
lib/celluloid/supervision/container/behavior/pool.rb
Celluloid.ClassMethods.pool_link
def pool_link(klass, config = {}, &block) Supervision::Container::Pool.new_link(pooling_options(config, block: block, actors: klass)) end
ruby
def pool_link(klass, config = {}, &block) Supervision::Container::Pool.new_link(pooling_options(config, block: block, actors: klass)) end
[ "def", "pool_link", "(", "klass", ",", "config", "=", "{", "}", ",", "&", "block", ")", "Supervision", "::", "Container", "::", "Pool", ".", "new_link", "(", "pooling_options", "(", "config", ",", "block", ":", "block", ",", "actors", ":", "klass", ")", ")", "end" ]
Same as pool, but links to the pool manager
[ "Same", "as", "pool", "but", "links", "to", "the", "pool", "manager" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/supervision/container/behavior/pool.rb#L18-L20
train
celluloid/celluloid
lib/celluloid.rb
Celluloid.ClassMethods.new_link
def new_link(*args, &block) raise NotActorError, "can't link outside actor context" unless Celluloid.actor? proxy = Cell.new(allocate, behavior_options, actor_options).proxy Actor.link(proxy) proxy._send_(:initialize, *args, &block) proxy end
ruby
def new_link(*args, &block) raise NotActorError, "can't link outside actor context" unless Celluloid.actor? proxy = Cell.new(allocate, behavior_options, actor_options).proxy Actor.link(proxy) proxy._send_(:initialize, *args, &block) proxy end
[ "def", "new_link", "(", "*", "args", ",", "&", "block", ")", "raise", "NotActorError", ",", "\"can't link outside actor context\"", "unless", "Celluloid", ".", "actor?", "proxy", "=", "Cell", ".", "new", "(", "allocate", ",", "behavior_options", ",", "actor_options", ")", ".", "proxy", "Actor", ".", "link", "(", "proxy", ")", "proxy", ".", "_send_", "(", ":initialize", ",", "args", ",", "block", ")", "proxy", "end" ]
Create a new actor and link to the current one
[ "Create", "a", "new", "actor", "and", "link", "to", "the", "current", "one" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid.rb#L205-L212
train
celluloid/celluloid
lib/celluloid/condition.rb
Celluloid.Condition.wait
def wait(timeout = nil) raise ConditionError, "cannot wait for signals while exclusive" if Celluloid.exclusive? if actor = Thread.current[:celluloid_actor] task = Task.current if timeout bt = caller timer = actor.timers.after(timeout) do exception = ConditionError.new("timeout after #{timeout.inspect} seconds") exception.set_backtrace bt task.resume exception end end else task = Thread.current end waiter = Waiter.new(self, task, Celluloid.mailbox, timeout) @mutex.synchronize do @waiters << waiter end result = Celluloid.suspend :condwait, waiter timer.cancel if timer raise result if result.is_a?(ConditionError) return yield(result) if block_given? result end
ruby
def wait(timeout = nil) raise ConditionError, "cannot wait for signals while exclusive" if Celluloid.exclusive? if actor = Thread.current[:celluloid_actor] task = Task.current if timeout bt = caller timer = actor.timers.after(timeout) do exception = ConditionError.new("timeout after #{timeout.inspect} seconds") exception.set_backtrace bt task.resume exception end end else task = Thread.current end waiter = Waiter.new(self, task, Celluloid.mailbox, timeout) @mutex.synchronize do @waiters << waiter end result = Celluloid.suspend :condwait, waiter timer.cancel if timer raise result if result.is_a?(ConditionError) return yield(result) if block_given? result end
[ "def", "wait", "(", "timeout", "=", "nil", ")", "raise", "ConditionError", ",", "\"cannot wait for signals while exclusive\"", "if", "Celluloid", ".", "exclusive?", "if", "actor", "=", "Thread", ".", "current", "[", ":celluloid_actor", "]", "task", "=", "Task", ".", "current", "if", "timeout", "bt", "=", "caller", "timer", "=", "actor", ".", "timers", ".", "after", "(", "timeout", ")", "do", "exception", "=", "ConditionError", ".", "new", "(", "\"timeout after #{timeout.inspect} seconds\"", ")", "exception", ".", "set_backtrace", "bt", "task", ".", "resume", "exception", "end", "end", "else", "task", "=", "Thread", ".", "current", "end", "waiter", "=", "Waiter", ".", "new", "(", "self", ",", "task", ",", "Celluloid", ".", "mailbox", ",", "timeout", ")", "@mutex", ".", "synchronize", "do", "@waiters", "<<", "waiter", "end", "result", "=", "Celluloid", ".", "suspend", ":condwait", ",", "waiter", "timer", ".", "cancel", "if", "timer", "raise", "result", "if", "result", ".", "is_a?", "(", "ConditionError", ")", "return", "yield", "(", "result", ")", "if", "block_given?", "result", "end" ]
Wait for the given signal and return the associated value
[ "Wait", "for", "the", "given", "signal", "and", "return", "the", "associated", "value" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/condition.rb#L36-L63
train
celluloid/celluloid
lib/celluloid/condition.rb
Celluloid.Condition.signal
def signal(value = nil) @mutex.synchronize do if waiter = @waiters.shift waiter << SignalConditionRequest.new(waiter.task, value) else Internals::Logger.with_backtrace(caller(3)) do |logger| logger.debug("Celluloid::Condition signaled spuriously") end end end end
ruby
def signal(value = nil) @mutex.synchronize do if waiter = @waiters.shift waiter << SignalConditionRequest.new(waiter.task, value) else Internals::Logger.with_backtrace(caller(3)) do |logger| logger.debug("Celluloid::Condition signaled spuriously") end end end end
[ "def", "signal", "(", "value", "=", "nil", ")", "@mutex", ".", "synchronize", "do", "if", "waiter", "=", "@waiters", ".", "shift", "waiter", "<<", "SignalConditionRequest", ".", "new", "(", "waiter", ".", "task", ",", "value", ")", "else", "Internals", "::", "Logger", ".", "with_backtrace", "(", "caller", "(", "3", ")", ")", "do", "|", "logger", "|", "logger", ".", "debug", "(", "\"Celluloid::Condition signaled spuriously\"", ")", "end", "end", "end", "end" ]
Send a signal to the first task waiting on this condition
[ "Send", "a", "signal", "to", "the", "first", "task", "waiting", "on", "this", "condition" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/condition.rb#L66-L76
train
celluloid/celluloid
lib/celluloid/condition.rb
Celluloid.Condition.broadcast
def broadcast(value = nil) @mutex.synchronize do @waiters.each { |waiter| waiter << SignalConditionRequest.new(waiter.task, value) } @waiters.clear end end
ruby
def broadcast(value = nil) @mutex.synchronize do @waiters.each { |waiter| waiter << SignalConditionRequest.new(waiter.task, value) } @waiters.clear end end
[ "def", "broadcast", "(", "value", "=", "nil", ")", "@mutex", ".", "synchronize", "do", "@waiters", ".", "each", "{", "|", "waiter", "|", "waiter", "<<", "SignalConditionRequest", ".", "new", "(", "waiter", ".", "task", ",", "value", ")", "}", "@waiters", ".", "clear", "end", "end" ]
Broadcast a value to all waiting tasks and threads
[ "Broadcast", "a", "value", "to", "all", "waiting", "tasks", "and", "threads" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/condition.rb#L79-L84
train
celluloid/celluloid
lib/celluloid/future.rb
Celluloid.Future.execute
def execute(receiver, method, args, block) @mutex.synchronize do raise "already calling" if @call @call = Call::Sync.new(self, method, args, block) end receiver << @call end
ruby
def execute(receiver, method, args, block) @mutex.synchronize do raise "already calling" if @call @call = Call::Sync.new(self, method, args, block) end receiver << @call end
[ "def", "execute", "(", "receiver", ",", "method", ",", "args", ",", "block", ")", "@mutex", ".", "synchronize", "do", "raise", "\"already calling\"", "if", "@call", "@call", "=", "Call", "::", "Sync", ".", "new", "(", "self", ",", "method", ",", "args", ",", "block", ")", "end", "receiver", "<<", "@call", "end" ]
Execute the given method in future context
[ "Execute", "the", "given", "method", "in", "future", "context" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/future.rb#L49-L56
train
celluloid/celluloid
lib/celluloid/future.rb
Celluloid.Future.value
def value(timeout = nil) ready = result = nil begin @mutex.lock if @ready ready = true result = @result else case @forwards when Array @forwards << Celluloid.mailbox when NilClass @forwards = Celluloid.mailbox else @forwards = [@forwards, Celluloid.mailbox] end end ensure @mutex.unlock end unless ready result = Celluloid.receive(timeout) do |msg| msg.is_a?(Future::Result) && msg.future == self end end if result result.respond_to?(:value) ? result.value : result else raise TimedOut, "Timed out" end end
ruby
def value(timeout = nil) ready = result = nil begin @mutex.lock if @ready ready = true result = @result else case @forwards when Array @forwards << Celluloid.mailbox when NilClass @forwards = Celluloid.mailbox else @forwards = [@forwards, Celluloid.mailbox] end end ensure @mutex.unlock end unless ready result = Celluloid.receive(timeout) do |msg| msg.is_a?(Future::Result) && msg.future == self end end if result result.respond_to?(:value) ? result.value : result else raise TimedOut, "Timed out" end end
[ "def", "value", "(", "timeout", "=", "nil", ")", "ready", "=", "result", "=", "nil", "begin", "@mutex", ".", "lock", "if", "@ready", "ready", "=", "true", "result", "=", "@result", "else", "case", "@forwards", "when", "Array", "@forwards", "<<", "Celluloid", ".", "mailbox", "when", "NilClass", "@forwards", "=", "Celluloid", ".", "mailbox", "else", "@forwards", "=", "[", "@forwards", ",", "Celluloid", ".", "mailbox", "]", "end", "end", "ensure", "@mutex", ".", "unlock", "end", "unless", "ready", "result", "=", "Celluloid", ".", "receive", "(", "timeout", ")", "do", "|", "msg", "|", "msg", ".", "is_a?", "(", "Future", "::", "Result", ")", "&&", "msg", ".", "future", "==", "self", "end", "end", "if", "result", "result", ".", "respond_to?", "(", ":value", ")", "?", "result", ".", "value", ":", "result", "else", "raise", "TimedOut", ",", "\"Timed out\"", "end", "end" ]
Obtain the value for this Future
[ "Obtain", "the", "value", "for", "this", "Future" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/future.rb#L64-L98
train
celluloid/celluloid
lib/celluloid/future.rb
Celluloid.Future.signal
def signal(value) return if @cancelled result = Result.new(value, self) @mutex.synchronize do raise "the future has already happened!" if @ready if @forwards @forwards.is_a?(Array) ? @forwards.each { |f| f << result } : @forwards << result end @result = result @ready = true end end
ruby
def signal(value) return if @cancelled result = Result.new(value, self) @mutex.synchronize do raise "the future has already happened!" if @ready if @forwards @forwards.is_a?(Array) ? @forwards.each { |f| f << result } : @forwards << result end @result = result @ready = true end end
[ "def", "signal", "(", "value", ")", "return", "if", "@cancelled", "result", "=", "Result", ".", "new", "(", "value", ",", "self", ")", "@mutex", ".", "synchronize", "do", "raise", "\"the future has already happened!\"", "if", "@ready", "if", "@forwards", "@forwards", ".", "is_a?", "(", "Array", ")", "?", "@forwards", ".", "each", "{", "|", "f", "|", "f", "<<", "result", "}", ":", "@forwards", "<<", "result", "end", "@result", "=", "result", "@ready", "=", "true", "end", "end" ]
Signal this future with the given result value
[ "Signal", "this", "future", "with", "the", "given", "result", "value" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/future.rb#L102-L116
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.run
def run while @running begin @timers.wait do |interval| interval = 0 if interval && interval < 0 if message = @mailbox.check(interval) handle_message(message) break unless @running end end rescue MailboxShutdown @running = false rescue MailboxDead # TODO: not tests (but fails occasionally in tests) @running = false end end shutdown rescue ::Exception => ex handle_crash(ex) raise unless ex.is_a?(StandardError) || ex.is_a?(Celluloid::Interruption) end
ruby
def run while @running begin @timers.wait do |interval| interval = 0 if interval && interval < 0 if message = @mailbox.check(interval) handle_message(message) break unless @running end end rescue MailboxShutdown @running = false rescue MailboxDead # TODO: not tests (but fails occasionally in tests) @running = false end end shutdown rescue ::Exception => ex handle_crash(ex) raise unless ex.is_a?(StandardError) || ex.is_a?(Celluloid::Interruption) end
[ "def", "run", "while", "@running", "begin", "@timers", ".", "wait", "do", "|", "interval", "|", "interval", "=", "0", "if", "interval", "&&", "interval", "<", "0", "if", "message", "=", "@mailbox", ".", "check", "(", "interval", ")", "handle_message", "(", "message", ")", "break", "unless", "@running", "end", "end", "rescue", "MailboxShutdown", "@running", "=", "false", "rescue", "MailboxDead", "# TODO: not tests (but fails occasionally in tests)", "@running", "=", "false", "end", "end", "shutdown", "rescue", "::", "Exception", "=>", "ex", "handle_crash", "(", "ex", ")", "raise", "unless", "ex", ".", "is_a?", "(", "StandardError", ")", "||", "ex", ".", "is_a?", "(", "Celluloid", "::", "Interruption", ")", "end" ]
Run the actor loop
[ "Run", "the", "actor", "loop" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L152-L176
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.linking_request
def linking_request(receiver, type) Celluloid.exclusive do receiver.mailbox << LinkingRequest.new(Actor.current, type) system_events = [] Timers::Wait.for(LINKING_TIMEOUT) do |remaining| begin message = @mailbox.receive(remaining) do |msg| msg.is_a?(LinkingResponse) && msg.actor.mailbox.address == receiver.mailbox.address && msg.type == type end rescue TaskTimeout next # IO reactor did something, no message in queue yet. end if message.instance_of? LinkingResponse # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Celluloid::Probe.actors_linked(self, receiver) if $CELLULOID_MONITORING # rubocop:enable Style/GlobalVars system_events.each { |ev| @mailbox << ev } return elsif message.is_a? SystemEvent # Queue up pending system events to be processed after we've successfully linked system_events << message else raise "Unexpected message type: #{message.class}. Expected LinkingResponse, NilClass, SystemEvent." end end raise TaskTimeout, "linking timeout of #{LINKING_TIMEOUT} seconds exceeded with receiver: #{receiver}" end end
ruby
def linking_request(receiver, type) Celluloid.exclusive do receiver.mailbox << LinkingRequest.new(Actor.current, type) system_events = [] Timers::Wait.for(LINKING_TIMEOUT) do |remaining| begin message = @mailbox.receive(remaining) do |msg| msg.is_a?(LinkingResponse) && msg.actor.mailbox.address == receiver.mailbox.address && msg.type == type end rescue TaskTimeout next # IO reactor did something, no message in queue yet. end if message.instance_of? LinkingResponse # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Celluloid::Probe.actors_linked(self, receiver) if $CELLULOID_MONITORING # rubocop:enable Style/GlobalVars system_events.each { |ev| @mailbox << ev } return elsif message.is_a? SystemEvent # Queue up pending system events to be processed after we've successfully linked system_events << message else raise "Unexpected message type: #{message.class}. Expected LinkingResponse, NilClass, SystemEvent." end end raise TaskTimeout, "linking timeout of #{LINKING_TIMEOUT} seconds exceeded with receiver: #{receiver}" end end
[ "def", "linking_request", "(", "receiver", ",", "type", ")", "Celluloid", ".", "exclusive", "do", "receiver", ".", "mailbox", "<<", "LinkingRequest", ".", "new", "(", "Actor", ".", "current", ",", "type", ")", "system_events", "=", "[", "]", "Timers", "::", "Wait", ".", "for", "(", "LINKING_TIMEOUT", ")", "do", "|", "remaining", "|", "begin", "message", "=", "@mailbox", ".", "receive", "(", "remaining", ")", "do", "|", "msg", "|", "msg", ".", "is_a?", "(", "LinkingResponse", ")", "&&", "msg", ".", "actor", ".", "mailbox", ".", "address", "==", "receiver", ".", "mailbox", ".", "address", "&&", "msg", ".", "type", "==", "type", "end", "rescue", "TaskTimeout", "next", "# IO reactor did something, no message in queue yet.", "end", "if", "message", ".", "instance_of?", "LinkingResponse", "# !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!", "# rubocop:disable Style/GlobalVars", "Celluloid", "::", "Probe", ".", "actors_linked", "(", "self", ",", "receiver", ")", "if", "$CELLULOID_MONITORING", "# rubocop:enable Style/GlobalVars", "system_events", ".", "each", "{", "|", "ev", "|", "@mailbox", "<<", "ev", "}", "return", "elsif", "message", ".", "is_a?", "SystemEvent", "# Queue up pending system events to be processed after we've successfully linked", "system_events", "<<", "message", "else", "raise", "\"Unexpected message type: #{message.class}. Expected LinkingResponse, NilClass, SystemEvent.\"", "end", "end", "raise", "TaskTimeout", ",", "\"linking timeout of #{LINKING_TIMEOUT} seconds exceeded with receiver: #{receiver}\"", "end", "end" ]
Perform a linking request with another actor
[ "Perform", "a", "linking", "request", "with", "another", "actor" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L184-L216
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.receive
def receive(timeout = nil, &block) loop do message = @receivers.receive(timeout, &block) return message unless message.is_a?(SystemEvent) handle_system_event(message) end end
ruby
def receive(timeout = nil, &block) loop do message = @receivers.receive(timeout, &block) return message unless message.is_a?(SystemEvent) handle_system_event(message) end end
[ "def", "receive", "(", "timeout", "=", "nil", ",", "&", "block", ")", "loop", "do", "message", "=", "@receivers", ".", "receive", "(", "timeout", ",", "block", ")", "return", "message", "unless", "message", ".", "is_a?", "(", "SystemEvent", ")", "handle_system_event", "(", "message", ")", "end", "end" ]
Receive an asynchronous message
[ "Receive", "an", "asynchronous", "message" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L234-L241
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.handle_message
def handle_message(message) # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Metrics/LineLength, Style/GlobalVars Internals::Logger.debug "Discarded message (unhandled): #{message}" if [email protected]_message(message) && [email protected]_message(message) && $CELLULOID_DEBUG # rubocop:enable Metrics/LineLength, Style/GlobalVars message end
ruby
def handle_message(message) # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Metrics/LineLength, Style/GlobalVars Internals::Logger.debug "Discarded message (unhandled): #{message}" if [email protected]_message(message) && [email protected]_message(message) && $CELLULOID_DEBUG # rubocop:enable Metrics/LineLength, Style/GlobalVars message end
[ "def", "handle_message", "(", "message", ")", "# !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!", "# rubocop:disable Metrics/LineLength, Style/GlobalVars", "Internals", "::", "Logger", ".", "debug", "\"Discarded message (unhandled): #{message}\"", "if", "!", "@handlers", ".", "handle_message", "(", "message", ")", "&&", "!", "@receivers", ".", "handle_message", "(", "message", ")", "&&", "$CELLULOID_DEBUG", "# rubocop:enable Metrics/LineLength, Style/GlobalVars", "message", "end" ]
Handle standard low-priority messages
[ "Handle", "standard", "low", "-", "priority", "messages" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L288-L295
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.handle_crash
def handle_crash(exception) # TODO: add meta info Internals::Logger.crash("Actor crashed!", exception) shutdown ExitEvent.new(behavior_proxy, exception) rescue => ex Internals::Logger.crash("Actor#handle_crash CRASHED!", ex) end
ruby
def handle_crash(exception) # TODO: add meta info Internals::Logger.crash("Actor crashed!", exception) shutdown ExitEvent.new(behavior_proxy, exception) rescue => ex Internals::Logger.crash("Actor#handle_crash CRASHED!", ex) end
[ "def", "handle_crash", "(", "exception", ")", "# TODO: add meta info", "Internals", "::", "Logger", ".", "crash", "(", "\"Actor crashed!\"", ",", "exception", ")", "shutdown", "ExitEvent", ".", "new", "(", "behavior_proxy", ",", "exception", ")", "rescue", "=>", "ex", "Internals", "::", "Logger", ".", "crash", "(", "\"Actor#handle_crash CRASHED!\"", ",", "ex", ")", "end" ]
Handle any exceptions that occur within a running actor
[ "Handle", "any", "exceptions", "that", "occur", "within", "a", "running", "actor" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L302-L308
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.shutdown
def shutdown(exit_event = ExitEvent.new(behavior_proxy)) @behavior.shutdown cleanup exit_event ensure Thread.current[:celluloid_actor] = nil Thread.current[:celluloid_mailbox] = nil end
ruby
def shutdown(exit_event = ExitEvent.new(behavior_proxy)) @behavior.shutdown cleanup exit_event ensure Thread.current[:celluloid_actor] = nil Thread.current[:celluloid_mailbox] = nil end
[ "def", "shutdown", "(", "exit_event", "=", "ExitEvent", ".", "new", "(", "behavior_proxy", ")", ")", "@behavior", ".", "shutdown", "cleanup", "exit_event", "ensure", "Thread", ".", "current", "[", ":celluloid_actor", "]", "=", "nil", "Thread", ".", "current", "[", ":celluloid_mailbox", "]", "=", "nil", "end" ]
Handle cleaning up this actor after it exits
[ "Handle", "cleaning", "up", "this", "actor", "after", "it", "exits" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L311-L317
train
celluloid/celluloid
lib/celluloid/actor.rb
Celluloid.Actor.cleanup
def cleanup(exit_event) # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Celluloid::Probe.actor_died(self) if $CELLULOID_MONITORING # rubocop:enable Style/GlobalVars @mailbox.shutdown @links.each do |actor| actor.mailbox << exit_event if actor.mailbox.alive? end tasks.to_a.each do |task| begin task.terminate rescue DeadTaskError # TODO: not tested (failed on Travis) end end rescue => ex # TODO: metadata Internals::Logger.crash("CLEANUP CRASHED!", ex) end
ruby
def cleanup(exit_event) # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Celluloid::Probe.actor_died(self) if $CELLULOID_MONITORING # rubocop:enable Style/GlobalVars @mailbox.shutdown @links.each do |actor| actor.mailbox << exit_event if actor.mailbox.alive? end tasks.to_a.each do |task| begin task.terminate rescue DeadTaskError # TODO: not tested (failed on Travis) end end rescue => ex # TODO: metadata Internals::Logger.crash("CLEANUP CRASHED!", ex) end
[ "def", "cleanup", "(", "exit_event", ")", "# !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!", "# rubocop:disable Style/GlobalVars", "Celluloid", "::", "Probe", ".", "actor_died", "(", "self", ")", "if", "$CELLULOID_MONITORING", "# rubocop:enable Style/GlobalVars", "@mailbox", ".", "shutdown", "@links", ".", "each", "do", "|", "actor", "|", "actor", ".", "mailbox", "<<", "exit_event", "if", "actor", ".", "mailbox", ".", "alive?", "end", "tasks", ".", "to_a", ".", "each", "do", "|", "task", "|", "begin", "task", ".", "terminate", "rescue", "DeadTaskError", "# TODO: not tested (failed on Travis)", "end", "end", "rescue", "=>", "ex", "# TODO: metadata", "Internals", "::", "Logger", ".", "crash", "(", "\"CLEANUP CRASHED!\"", ",", "ex", ")", "end" ]
Clean up after this actor
[ "Clean", "up", "after", "this", "actor" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/actor.rb#L320-L341
train
celluloid/celluloid
lib/celluloid/task.rb
Celluloid.Task.suspend
def suspend(status) raise "Cannot suspend while in exclusive mode" if exclusive? raise "Cannot suspend a task from outside of itself" unless Task.current == self @status = status # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars if $CELLULOID_DEBUG && @dangerous_suspend Internals::Logger.with_backtrace(caller[2...8]) do |logger| logger.warn "Dangerously suspending task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" end end # rubocop:enable Style/GlobalVars value = signal @status = :running raise value if value.is_a?(Celluloid::Interruption) value end
ruby
def suspend(status) raise "Cannot suspend while in exclusive mode" if exclusive? raise "Cannot suspend a task from outside of itself" unless Task.current == self @status = status # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars if $CELLULOID_DEBUG && @dangerous_suspend Internals::Logger.with_backtrace(caller[2...8]) do |logger| logger.warn "Dangerously suspending task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" end end # rubocop:enable Style/GlobalVars value = signal @status = :running raise value if value.is_a?(Celluloid::Interruption) value end
[ "def", "suspend", "(", "status", ")", "raise", "\"Cannot suspend while in exclusive mode\"", "if", "exclusive?", "raise", "\"Cannot suspend a task from outside of itself\"", "unless", "Task", ".", "current", "==", "self", "@status", "=", "status", "# !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!", "# rubocop:disable Style/GlobalVars", "if", "$CELLULOID_DEBUG", "&&", "@dangerous_suspend", "Internals", "::", "Logger", ".", "with_backtrace", "(", "caller", "[", "2", "...", "8", "]", ")", "do", "|", "logger", "|", "logger", ".", "warn", "\"Dangerously suspending task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}\"", "end", "end", "# rubocop:enable Style/GlobalVars", "value", "=", "signal", "@status", "=", ":running", "raise", "value", "if", "value", ".", "is_a?", "(", "Celluloid", "::", "Interruption", ")", "value", "end" ]
Suspend the current task, changing the status to the given argument
[ "Suspend", "the", "current", "task", "changing", "the", "status", "to", "the", "given", "argument" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/task.rb#L60-L80
train
celluloid/celluloid
lib/celluloid/task.rb
Celluloid.Task.resume
def resume(value = nil) guard "Cannot resume a task from inside of a task" if Thread.current[:celluloid_task] if running? deliver(value) else # rubocop:disable Metrics/LineLength Internals::Logger.warn "Attempted to resume a dead task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" # rubocop:enable Metrics/LineLength end nil end
ruby
def resume(value = nil) guard "Cannot resume a task from inside of a task" if Thread.current[:celluloid_task] if running? deliver(value) else # rubocop:disable Metrics/LineLength Internals::Logger.warn "Attempted to resume a dead task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" # rubocop:enable Metrics/LineLength end nil end
[ "def", "resume", "(", "value", "=", "nil", ")", "guard", "\"Cannot resume a task from inside of a task\"", "if", "Thread", ".", "current", "[", ":celluloid_task", "]", "if", "running?", "deliver", "(", "value", ")", "else", "# rubocop:disable Metrics/LineLength", "Internals", "::", "Logger", ".", "warn", "\"Attempted to resume a dead task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}\"", "# rubocop:enable Metrics/LineLength", "end", "nil", "end" ]
Resume a suspended task, giving it a value to return if needed
[ "Resume", "a", "suspended", "task", "giving", "it", "a", "value", "to", "return", "if", "needed" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/task.rb#L83-L93
train
celluloid/celluloid
lib/celluloid/task.rb
Celluloid.Task.terminate
def terminate raise "Cannot terminate an exclusive task" if exclusive? if running? # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars if $CELLULOID_DEBUG Internals::Logger.with_backtrace(backtrace) do |logger| type = @dangerous_suspend ? :warn : :debug logger.send(type, "Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}") end end # rubocop:enable Style/GlobalVars exception = TaskTerminated.new("task was terminated") exception.set_backtrace(caller) resume exception else raise DeadTaskError, "task is already dead" end end
ruby
def terminate raise "Cannot terminate an exclusive task" if exclusive? if running? # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars if $CELLULOID_DEBUG Internals::Logger.with_backtrace(backtrace) do |logger| type = @dangerous_suspend ? :warn : :debug logger.send(type, "Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}") end end # rubocop:enable Style/GlobalVars exception = TaskTerminated.new("task was terminated") exception.set_backtrace(caller) resume exception else raise DeadTaskError, "task is already dead" end end
[ "def", "terminate", "raise", "\"Cannot terminate an exclusive task\"", "if", "exclusive?", "if", "running?", "# !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!", "# rubocop:disable Style/GlobalVars", "if", "$CELLULOID_DEBUG", "Internals", "::", "Logger", ".", "with_backtrace", "(", "backtrace", ")", "do", "|", "logger", "|", "type", "=", "@dangerous_suspend", "?", ":warn", ":", ":debug", "logger", ".", "send", "(", "type", ",", "\"Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}\"", ")", "end", "end", "# rubocop:enable Style/GlobalVars", "exception", "=", "TaskTerminated", ".", "new", "(", "\"task was terminated\"", ")", "exception", ".", "set_backtrace", "(", "caller", ")", "resume", "exception", "else", "raise", "DeadTaskError", ",", "\"task is already dead\"", "end", "end" ]
Terminate this task
[ "Terminate", "this", "task" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/task.rb#L110-L130
train
celluloid/celluloid
lib/celluloid/cell.rb
Celluloid.Cell.shutdown
def shutdown return unless @finalizer && @subject.respond_to?(@finalizer, true) task(:finalizer, @finalizer, { call: @finalizer, subject: @subject }, dangerous_suspend: true, &Cell.shutdown) end
ruby
def shutdown return unless @finalizer && @subject.respond_to?(@finalizer, true) task(:finalizer, @finalizer, { call: @finalizer, subject: @subject }, dangerous_suspend: true, &Cell.shutdown) end
[ "def", "shutdown", "return", "unless", "@finalizer", "&&", "@subject", ".", "respond_to?", "(", "@finalizer", ",", "true", ")", "task", "(", ":finalizer", ",", "@finalizer", ",", "{", "call", ":", "@finalizer", ",", "subject", ":", "@subject", "}", ",", "dangerous_suspend", ":", "true", ",", "Cell", ".", "shutdown", ")", "end" ]
Run the user-defined finalizer, if one is set
[ "Run", "the", "user", "-", "defined", "finalizer", "if", "one", "is", "set" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/cell.rb#L90-L95
train
celluloid/celluloid
lib/celluloid/mailbox.rb
Celluloid.Mailbox.<<
def <<(message) @mutex.lock begin if mailbox_full || @dead dead_letter(message) return end if message.is_a?(SystemEvent) # SystemEvents are high priority messages so they get added to the # head of our message queue instead of the end @messages.unshift message else @messages << message end @condition.signal nil ensure begin @mutex.unlock rescue nil end end end
ruby
def <<(message) @mutex.lock begin if mailbox_full || @dead dead_letter(message) return end if message.is_a?(SystemEvent) # SystemEvents are high priority messages so they get added to the # head of our message queue instead of the end @messages.unshift message else @messages << message end @condition.signal nil ensure begin @mutex.unlock rescue nil end end end
[ "def", "<<", "(", "message", ")", "@mutex", ".", "lock", "begin", "if", "mailbox_full", "||", "@dead", "dead_letter", "(", "message", ")", "return", "end", "if", "message", ".", "is_a?", "(", "SystemEvent", ")", "# SystemEvents are high priority messages so they get added to the", "# head of our message queue instead of the end", "@messages", ".", "unshift", "message", "else", "@messages", "<<", "message", "end", "@condition", ".", "signal", "nil", "ensure", "begin", "@mutex", ".", "unlock", "rescue", "nil", "end", "end", "end" ]
Add a message to the Mailbox
[ "Add", "a", "message", "to", "the", "Mailbox" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/mailbox.rb#L24-L48
train
celluloid/celluloid
lib/celluloid/mailbox.rb
Celluloid.Mailbox.check
def check(timeout = nil, &block) message = nil @mutex.lock begin raise MailboxDead, "attempted to receive from a dead mailbox" if @dead message = nil Timers::Wait.for(timeout) do |remaining| message = next_message(&block) break if message @condition.wait(@mutex, remaining) end ensure begin @mutex.unlock rescue nil end end message end
ruby
def check(timeout = nil, &block) message = nil @mutex.lock begin raise MailboxDead, "attempted to receive from a dead mailbox" if @dead message = nil Timers::Wait.for(timeout) do |remaining| message = next_message(&block) break if message @condition.wait(@mutex, remaining) end ensure begin @mutex.unlock rescue nil end end message end
[ "def", "check", "(", "timeout", "=", "nil", ",", "&", "block", ")", "message", "=", "nil", "@mutex", ".", "lock", "begin", "raise", "MailboxDead", ",", "\"attempted to receive from a dead mailbox\"", "if", "@dead", "message", "=", "nil", "Timers", "::", "Wait", ".", "for", "(", "timeout", ")", "do", "|", "remaining", "|", "message", "=", "next_message", "(", "block", ")", "break", "if", "message", "@condition", ".", "wait", "(", "@mutex", ",", "remaining", ")", "end", "ensure", "begin", "@mutex", ".", "unlock", "rescue", "nil", "end", "end", "message", "end" ]
Receive a message from the Mailbox. May return nil and may return before the specified timeout.
[ "Receive", "a", "message", "from", "the", "Mailbox", ".", "May", "return", "nil", "and", "may", "return", "before", "the", "specified", "timeout", "." ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/mailbox.rb#L52-L76
train
celluloid/celluloid
lib/celluloid/mailbox.rb
Celluloid.Mailbox.receive
def receive(timeout = nil, &block) message = nil Timers::Wait.for(timeout) do |_remaining| message = check(timeout, &block) break if message end return message if message raise TaskTimeout, "receive timeout exceeded" end
ruby
def receive(timeout = nil, &block) message = nil Timers::Wait.for(timeout) do |_remaining| message = check(timeout, &block) break if message end return message if message raise TaskTimeout, "receive timeout exceeded" end
[ "def", "receive", "(", "timeout", "=", "nil", ",", "&", "block", ")", "message", "=", "nil", "Timers", "::", "Wait", ".", "for", "(", "timeout", ")", "do", "|", "_remaining", "|", "message", "=", "check", "(", "timeout", ",", "block", ")", "break", "if", "message", "end", "return", "message", "if", "message", "raise", "TaskTimeout", ",", "\"receive timeout exceeded\"", "end" ]
Receive a letter from the mailbox. Guaranteed to return a message. If timeout is exceeded, raise a TaskTimeout.
[ "Receive", "a", "letter", "from", "the", "mailbox", ".", "Guaranteed", "to", "return", "a", "message", ".", "If", "timeout", "is", "exceeded", "raise", "a", "TaskTimeout", "." ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/mailbox.rb#L80-L88
train
celluloid/celluloid
lib/celluloid/mailbox.rb
Celluloid.Mailbox.shutdown
def shutdown raise MailboxDead, "mailbox already shutdown" if @dead @mutex.lock begin yield if block_given? messages = @messages @messages = [] @dead = true ensure begin @mutex.unlock rescue nil end end messages.each do |msg| dead_letter msg msg.cleanup if msg.respond_to? :cleanup end true end
ruby
def shutdown raise MailboxDead, "mailbox already shutdown" if @dead @mutex.lock begin yield if block_given? messages = @messages @messages = [] @dead = true ensure begin @mutex.unlock rescue nil end end messages.each do |msg| dead_letter msg msg.cleanup if msg.respond_to? :cleanup end true end
[ "def", "shutdown", "raise", "MailboxDead", ",", "\"mailbox already shutdown\"", "if", "@dead", "@mutex", ".", "lock", "begin", "yield", "if", "block_given?", "messages", "=", "@messages", "@messages", "=", "[", "]", "@dead", "=", "true", "ensure", "begin", "@mutex", ".", "unlock", "rescue", "nil", "end", "end", "messages", ".", "each", "do", "|", "msg", "|", "dead_letter", "msg", "msg", ".", "cleanup", "if", "msg", ".", "respond_to?", ":cleanup", "end", "true", "end" ]
Shut down this mailbox and clean up its contents
[ "Shut", "down", "this", "mailbox", "and", "clean", "up", "its", "contents" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/mailbox.rb#L91-L113
train
celluloid/celluloid
lib/celluloid/mailbox.rb
Celluloid.Mailbox.next_message
def next_message message = nil if block_given? index = @messages.index do |msg| yield(msg) || msg.is_a?(SystemEvent) end message = @messages.slice!(index, 1).first if index else message = @messages.shift end message end
ruby
def next_message message = nil if block_given? index = @messages.index do |msg| yield(msg) || msg.is_a?(SystemEvent) end message = @messages.slice!(index, 1).first if index else message = @messages.shift end message end
[ "def", "next_message", "message", "=", "nil", "if", "block_given?", "index", "=", "@messages", ".", "index", "do", "|", "msg", "|", "yield", "(", "msg", ")", "||", "msg", ".", "is_a?", "(", "SystemEvent", ")", "end", "message", "=", "@messages", ".", "slice!", "(", "index", ",", "1", ")", ".", "first", "if", "index", "else", "message", "=", "@messages", ".", "shift", "end", "message", "end" ]
Retrieve the next message in the mailbox
[ "Retrieve", "the", "next", "message", "in", "the", "mailbox" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/mailbox.rb#L143-L157
train
celluloid/celluloid
lib/celluloid/logging/incident.rb
Celluloid.Incident.merge
def merge(*other_incidents) merged_events = other_incidents.flatten.inject(events) do |events, incident| events += incident.events end Incident.new(merged_events.sort, triggering_event) end
ruby
def merge(*other_incidents) merged_events = other_incidents.flatten.inject(events) do |events, incident| events += incident.events end Incident.new(merged_events.sort, triggering_event) end
[ "def", "merge", "(", "*", "other_incidents", ")", "merged_events", "=", "other_incidents", ".", "flatten", ".", "inject", "(", "events", ")", "do", "|", "events", ",", "incident", "|", "events", "+=", "incident", ".", "events", "end", "Incident", ".", "new", "(", "merged_events", ".", "sort", ",", "triggering_event", ")", "end" ]
Merge two incidents together. This may be useful if two incidents occur at the same time.
[ "Merge", "two", "incidents", "together", ".", "This", "may", "be", "useful", "if", "two", "incidents", "occur", "at", "the", "same", "time", "." ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/logging/incident.rb#L14-L19
train
celluloid/celluloid
lib/celluloid/system_events.rb
Celluloid.Actor.handle_system_event
def handle_system_event(event) if handler = SystemEvent.handle(event.class) send(handler, event) else # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Internals::Logger.debug "Discarded message (unhandled): #{message}" if $CELLULOID_DEBUG # rubocop:enable Style/GlobalVars end end
ruby
def handle_system_event(event) if handler = SystemEvent.handle(event.class) send(handler, event) else # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Internals::Logger.debug "Discarded message (unhandled): #{message}" if $CELLULOID_DEBUG # rubocop:enable Style/GlobalVars end end
[ "def", "handle_system_event", "(", "event", ")", "if", "handler", "=", "SystemEvent", ".", "handle", "(", "event", ".", "class", ")", "send", "(", "handler", ",", "event", ")", "else", "# !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!!", "# rubocop:disable Style/GlobalVars", "Internals", "::", "Logger", ".", "debug", "\"Discarded message (unhandled): #{message}\"", "if", "$CELLULOID_DEBUG", "# rubocop:enable Style/GlobalVars", "end", "end" ]
Handle high-priority system event messages
[ "Handle", "high", "-", "priority", "system", "event", "messages" ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/system_events.rb#L4-L13
train
celluloid/celluloid
lib/celluloid/logging/incident_logger.rb
Celluloid.IncidentLogger.add
def add(severity, message = nil, progname = nil, &block) progname ||= @progname severity ||= UNKNOWN return event.id if severity < @level if message.nil? && !block_given? message = progname progname = @progname end event = LogEvent.new(severity, message, progname, &block) @buffers[progname][severity] << event if severity >= @threshold begin Celluloid::Notifications.notifier.async.publish(incident_topic, create_incident(event)) rescue => ex @fallback_logger.error(ex) end end event.id end
ruby
def add(severity, message = nil, progname = nil, &block) progname ||= @progname severity ||= UNKNOWN return event.id if severity < @level if message.nil? && !block_given? message = progname progname = @progname end event = LogEvent.new(severity, message, progname, &block) @buffers[progname][severity] << event if severity >= @threshold begin Celluloid::Notifications.notifier.async.publish(incident_topic, create_incident(event)) rescue => ex @fallback_logger.error(ex) end end event.id end
[ "def", "add", "(", "severity", ",", "message", "=", "nil", ",", "progname", "=", "nil", ",", "&", "block", ")", "progname", "||=", "@progname", "severity", "||=", "UNKNOWN", "return", "event", ".", "id", "if", "severity", "<", "@level", "if", "message", ".", "nil?", "&&", "!", "block_given?", "message", "=", "progname", "progname", "=", "@progname", "end", "event", "=", "LogEvent", ".", "new", "(", "severity", ",", "message", ",", "progname", ",", "block", ")", "@buffers", "[", "progname", "]", "[", "severity", "]", "<<", "event", "if", "severity", ">=", "@threshold", "begin", "Celluloid", "::", "Notifications", ".", "notifier", ".", "async", ".", "publish", "(", "incident_topic", ",", "create_incident", "(", "event", ")", ")", "rescue", "=>", "ex", "@fallback_logger", ".", "error", "(", "ex", ")", "end", "end", "event", ".", "id", "end" ]
Create a new IncidentLogger. add an event.
[ "Create", "a", "new", "IncidentLogger", ".", "add", "an", "event", "." ]
2c21bbc481ae65ba527f415f52df4ae99700b72f
https://github.com/celluloid/celluloid/blob/2c21bbc481ae65ba527f415f52df4ae99700b72f/lib/celluloid/logging/incident_logger.rb#L66-L89
train
sup-heliotrope/sup
lib/sup/crypto.rb
Redwood.CryptoManager.decrypt
def decrypt payload, armor=false # a RubyMail::Message object return unknown_status(@not_working_reason) unless @not_working_reason.nil? gpg_opts = {:protocol => GPGME::PROTOCOL_OpenPGP} gpg_opts = HookManager.run("gpg-options", {:operation => "decrypt", :options => gpg_opts}) || gpg_opts ctx = GPGME::Ctx.new(gpg_opts) cipher_data = GPGME::Data.from_str(format_payload(payload)) if GPGME::Data.respond_to?('empty') plain_data = GPGME::Data.empty else plain_data = GPGME::Data.empty! end begin ctx.decrypt_verify(cipher_data, plain_data) rescue GPGME::Error => exc return Chunk::CryptoNotice.new(:invalid, "This message could not be decrypted", gpgme_exc_msg(exc.message)) end begin sig = self.verified_ok? ctx.verify_result rescue ArgumentError => exc sig = unknown_status [gpgme_exc_msg(exc.message)] end plain_data.seek(0, IO::SEEK_SET) output = plain_data.read output.transcode(Encoding::ASCII_8BIT, output.encoding) ## TODO: test to see if it is still necessary to do a 2nd run if verify ## fails. # ## check for a valid signature in an extra run because gpg aborts if the ## signature cannot be verified (but it is still able to decrypt) #sigoutput = run_gpg "#{payload_fn.path}" #sig = self.old_verified_ok? sigoutput, $? if armor msg = RMail::Message.new # Look for Charset, they are put before the base64 crypted part charsets = payload.body.split("\n").grep(/^Charset:/) if !charsets.empty? and charsets[0] =~ /^Charset: (.+)$/ output.transcode($encoding, $1) end msg.body = output else # It appears that some clients use Windows new lines - CRLF - but RMail # splits the body and header on "\n\n". So to allow the parse below to # succeed, we will convert the newlines to what RMail expects output = output.gsub(/\r\n/, "\n") # This is gross. This decrypted payload could very well be a multipart # element itself, as opposed to a simple payload. For example, a # multipart/signed element, like those generated by Mutt when encrypting # and signing a message (instead of just clearsigning the body). # Supposedly, decrypted_payload being a multipart element ought to work # out nicely because Message::multipart_encrypted_to_chunks() runs the # decrypted message through message_to_chunks() again to get any # children. However, it does not work as intended because these inner # payloads need not carry a MIME-Version header, yet they are fed to # RMail as a top-level message, for which the MIME-Version header is # required. This causes for the part not to be detected as multipart, # hence being shown as an attachment. If we detect this is happening, # we force the decrypted payload to be interpreted as MIME. msg = RMail::Parser.read output if msg.header.content_type =~ %r{^multipart/} && !msg.multipart? output = "MIME-Version: 1.0\n" + output output.fix_encoding! msg = RMail::Parser.read output end end notice = Chunk::CryptoNotice.new :valid, "This message has been decrypted for display" [notice, sig, msg] end
ruby
def decrypt payload, armor=false # a RubyMail::Message object return unknown_status(@not_working_reason) unless @not_working_reason.nil? gpg_opts = {:protocol => GPGME::PROTOCOL_OpenPGP} gpg_opts = HookManager.run("gpg-options", {:operation => "decrypt", :options => gpg_opts}) || gpg_opts ctx = GPGME::Ctx.new(gpg_opts) cipher_data = GPGME::Data.from_str(format_payload(payload)) if GPGME::Data.respond_to?('empty') plain_data = GPGME::Data.empty else plain_data = GPGME::Data.empty! end begin ctx.decrypt_verify(cipher_data, plain_data) rescue GPGME::Error => exc return Chunk::CryptoNotice.new(:invalid, "This message could not be decrypted", gpgme_exc_msg(exc.message)) end begin sig = self.verified_ok? ctx.verify_result rescue ArgumentError => exc sig = unknown_status [gpgme_exc_msg(exc.message)] end plain_data.seek(0, IO::SEEK_SET) output = plain_data.read output.transcode(Encoding::ASCII_8BIT, output.encoding) ## TODO: test to see if it is still necessary to do a 2nd run if verify ## fails. # ## check for a valid signature in an extra run because gpg aborts if the ## signature cannot be verified (but it is still able to decrypt) #sigoutput = run_gpg "#{payload_fn.path}" #sig = self.old_verified_ok? sigoutput, $? if armor msg = RMail::Message.new # Look for Charset, they are put before the base64 crypted part charsets = payload.body.split("\n").grep(/^Charset:/) if !charsets.empty? and charsets[0] =~ /^Charset: (.+)$/ output.transcode($encoding, $1) end msg.body = output else # It appears that some clients use Windows new lines - CRLF - but RMail # splits the body and header on "\n\n". So to allow the parse below to # succeed, we will convert the newlines to what RMail expects output = output.gsub(/\r\n/, "\n") # This is gross. This decrypted payload could very well be a multipart # element itself, as opposed to a simple payload. For example, a # multipart/signed element, like those generated by Mutt when encrypting # and signing a message (instead of just clearsigning the body). # Supposedly, decrypted_payload being a multipart element ought to work # out nicely because Message::multipart_encrypted_to_chunks() runs the # decrypted message through message_to_chunks() again to get any # children. However, it does not work as intended because these inner # payloads need not carry a MIME-Version header, yet they are fed to # RMail as a top-level message, for which the MIME-Version header is # required. This causes for the part not to be detected as multipart, # hence being shown as an attachment. If we detect this is happening, # we force the decrypted payload to be interpreted as MIME. msg = RMail::Parser.read output if msg.header.content_type =~ %r{^multipart/} && !msg.multipart? output = "MIME-Version: 1.0\n" + output output.fix_encoding! msg = RMail::Parser.read output end end notice = Chunk::CryptoNotice.new :valid, "This message has been decrypted for display" [notice, sig, msg] end
[ "def", "decrypt", "payload", ",", "armor", "=", "false", "# a RubyMail::Message object", "return", "unknown_status", "(", "@not_working_reason", ")", "unless", "@not_working_reason", ".", "nil?", "gpg_opts", "=", "{", ":protocol", "=>", "GPGME", "::", "PROTOCOL_OpenPGP", "}", "gpg_opts", "=", "HookManager", ".", "run", "(", "\"gpg-options\"", ",", "{", ":operation", "=>", "\"decrypt\"", ",", ":options", "=>", "gpg_opts", "}", ")", "||", "gpg_opts", "ctx", "=", "GPGME", "::", "Ctx", ".", "new", "(", "gpg_opts", ")", "cipher_data", "=", "GPGME", "::", "Data", ".", "from_str", "(", "format_payload", "(", "payload", ")", ")", "if", "GPGME", "::", "Data", ".", "respond_to?", "(", "'empty'", ")", "plain_data", "=", "GPGME", "::", "Data", ".", "empty", "else", "plain_data", "=", "GPGME", "::", "Data", ".", "empty!", "end", "begin", "ctx", ".", "decrypt_verify", "(", "cipher_data", ",", "plain_data", ")", "rescue", "GPGME", "::", "Error", "=>", "exc", "return", "Chunk", "::", "CryptoNotice", ".", "new", "(", ":invalid", ",", "\"This message could not be decrypted\"", ",", "gpgme_exc_msg", "(", "exc", ".", "message", ")", ")", "end", "begin", "sig", "=", "self", ".", "verified_ok?", "ctx", ".", "verify_result", "rescue", "ArgumentError", "=>", "exc", "sig", "=", "unknown_status", "[", "gpgme_exc_msg", "(", "exc", ".", "message", ")", "]", "end", "plain_data", ".", "seek", "(", "0", ",", "IO", "::", "SEEK_SET", ")", "output", "=", "plain_data", ".", "read", "output", ".", "transcode", "(", "Encoding", "::", "ASCII_8BIT", ",", "output", ".", "encoding", ")", "## TODO: test to see if it is still necessary to do a 2nd run if verify", "## fails.", "#", "## check for a valid signature in an extra run because gpg aborts if the", "## signature cannot be verified (but it is still able to decrypt)", "#sigoutput = run_gpg \"#{payload_fn.path}\"", "#sig = self.old_verified_ok? sigoutput, $?", "if", "armor", "msg", "=", "RMail", "::", "Message", ".", "new", "# Look for Charset, they are put before the base64 crypted part", "charsets", "=", "payload", ".", "body", ".", "split", "(", "\"\\n\"", ")", ".", "grep", "(", "/", "/", ")", "if", "!", "charsets", ".", "empty?", "and", "charsets", "[", "0", "]", "=~", "/", "/", "output", ".", "transcode", "(", "$encoding", ",", "$1", ")", "end", "msg", ".", "body", "=", "output", "else", "# It appears that some clients use Windows new lines - CRLF - but RMail", "# splits the body and header on \"\\n\\n\". So to allow the parse below to", "# succeed, we will convert the newlines to what RMail expects", "output", "=", "output", ".", "gsub", "(", "/", "\\r", "\\n", "/", ",", "\"\\n\"", ")", "# This is gross. This decrypted payload could very well be a multipart", "# element itself, as opposed to a simple payload. For example, a", "# multipart/signed element, like those generated by Mutt when encrypting", "# and signing a message (instead of just clearsigning the body).", "# Supposedly, decrypted_payload being a multipart element ought to work", "# out nicely because Message::multipart_encrypted_to_chunks() runs the", "# decrypted message through message_to_chunks() again to get any", "# children. However, it does not work as intended because these inner", "# payloads need not carry a MIME-Version header, yet they are fed to", "# RMail as a top-level message, for which the MIME-Version header is", "# required. This causes for the part not to be detected as multipart,", "# hence being shown as an attachment. If we detect this is happening,", "# we force the decrypted payload to be interpreted as MIME.", "msg", "=", "RMail", "::", "Parser", ".", "read", "output", "if", "msg", ".", "header", ".", "content_type", "=~", "%r{", "}", "&&", "!", "msg", ".", "multipart?", "output", "=", "\"MIME-Version: 1.0\\n\"", "+", "output", "output", ".", "fix_encoding!", "msg", "=", "RMail", "::", "Parser", ".", "read", "output", "end", "end", "notice", "=", "Chunk", "::", "CryptoNotice", ".", "new", ":valid", ",", "\"This message has been decrypted for display\"", "[", "notice", ",", "sig", ",", "msg", "]", "end" ]
returns decrypted_message, status, desc, lines
[ "returns", "decrypted_message", "status", "desc", "lines" ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/crypto.rb#L288-L358
train
sup-heliotrope/sup
lib/sup/logger.rb
Redwood.Logger.send_message
def send_message m @mutex.synchronize do @sinks.each do |sink| sink << m sink.flush if sink.respond_to?(:flush) and level == "debug" end @buf << m end end
ruby
def send_message m @mutex.synchronize do @sinks.each do |sink| sink << m sink.flush if sink.respond_to?(:flush) and level == "debug" end @buf << m end end
[ "def", "send_message", "m", "@mutex", ".", "synchronize", "do", "@sinks", ".", "each", "do", "|", "sink", "|", "sink", "<<", "m", "sink", ".", "flush", "if", "sink", ".", "respond_to?", "(", ":flush", ")", "and", "level", "==", "\"debug\"", "end", "@buf", "<<", "m", "end", "end" ]
actually distribute the message
[ "actually", "distribute", "the", "message" ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/logger.rb#L61-L69
train
sup-heliotrope/sup
lib/sup/mbox.rb
Redwood.MBox.each_raw_message_line
def each_raw_message_line offset @mutex.synchronize do ensure_open @f.seek offset until @f.eof? || MBox::is_break_line?(l = @f.gets) yield l end end end
ruby
def each_raw_message_line offset @mutex.synchronize do ensure_open @f.seek offset until @f.eof? || MBox::is_break_line?(l = @f.gets) yield l end end end
[ "def", "each_raw_message_line", "offset", "@mutex", ".", "synchronize", "do", "ensure_open", "@f", ".", "seek", "offset", "until", "@f", ".", "eof?", "||", "MBox", "::", "is_break_line?", "(", "l", "=", "@f", ".", "gets", ")", "yield", "l", "end", "end", "end" ]
apparently it's a million times faster to call this directly if we're just moving messages around on disk, than reading things into memory with raw_message.
[ "apparently", "it", "s", "a", "million", "times", "faster", "to", "call", "this", "directly", "if", "we", "re", "just", "moving", "messages", "around", "on", "disk", "than", "reading", "things", "into", "memory", "with", "raw_message", "." ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/mbox.rb#L130-L138
train
sup-heliotrope/sup
lib/sup/account.rb
Redwood.AccountManager.add_account
def add_account hash, default=false raise ArgumentError, "no email specified for account" unless hash[:email] unless default [:name, :sendmail, :signature, :gpgkey].each { |k| hash[k] ||= @default_account.send(k) } end hash[:alternates] ||= [] fail "alternative emails are not an array: #{hash[:alternates]}" unless hash[:alternates].kind_of? Array [:name, :signature].each { |x| hash[x] ? hash[x].fix_encoding! : nil } a = Account.new hash @accounts[a] = true if default raise ArgumentError, "multiple default accounts" if @default_account @default_account = a end ([hash[:email]] + hash[:alternates]).each do |email| next if @email_map.member? email @email_map[email] = a end hash[:regexen].each do |re| @regexen[Regexp.new(re)] = a end if hash[:regexen] end
ruby
def add_account hash, default=false raise ArgumentError, "no email specified for account" unless hash[:email] unless default [:name, :sendmail, :signature, :gpgkey].each { |k| hash[k] ||= @default_account.send(k) } end hash[:alternates] ||= [] fail "alternative emails are not an array: #{hash[:alternates]}" unless hash[:alternates].kind_of? Array [:name, :signature].each { |x| hash[x] ? hash[x].fix_encoding! : nil } a = Account.new hash @accounts[a] = true if default raise ArgumentError, "multiple default accounts" if @default_account @default_account = a end ([hash[:email]] + hash[:alternates]).each do |email| next if @email_map.member? email @email_map[email] = a end hash[:regexen].each do |re| @regexen[Regexp.new(re)] = a end if hash[:regexen] end
[ "def", "add_account", "hash", ",", "default", "=", "false", "raise", "ArgumentError", ",", "\"no email specified for account\"", "unless", "hash", "[", ":email", "]", "unless", "default", "[", ":name", ",", ":sendmail", ",", ":signature", ",", ":gpgkey", "]", ".", "each", "{", "|", "k", "|", "hash", "[", "k", "]", "||=", "@default_account", ".", "send", "(", "k", ")", "}", "end", "hash", "[", ":alternates", "]", "||=", "[", "]", "fail", "\"alternative emails are not an array: #{hash[:alternates]}\"", "unless", "hash", "[", ":alternates", "]", ".", "kind_of?", "Array", "[", ":name", ",", ":signature", "]", ".", "each", "{", "|", "x", "|", "hash", "[", "x", "]", "?", "hash", "[", "x", "]", ".", "fix_encoding!", ":", "nil", "}", "a", "=", "Account", ".", "new", "hash", "@accounts", "[", "a", "]", "=", "true", "if", "default", "raise", "ArgumentError", ",", "\"multiple default accounts\"", "if", "@default_account", "@default_account", "=", "a", "end", "(", "[", "hash", "[", ":email", "]", "]", "+", "hash", "[", ":alternates", "]", ")", ".", "each", "do", "|", "email", "|", "next", "if", "@email_map", ".", "member?", "email", "@email_map", "[", "email", "]", "=", "a", "end", "hash", "[", ":regexen", "]", ".", "each", "do", "|", "re", "|", "@regexen", "[", "Regexp", ".", "new", "(", "re", ")", "]", "=", "a", "end", "if", "hash", "[", ":regexen", "]", "end" ]
must be called first with the default account. fills in missing values from the default account.
[ "must", "be", "called", "first", "with", "the", "default", "account", ".", "fills", "in", "missing", "values", "from", "the", "default", "account", "." ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/account.rb#L47-L73
train
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.select
def select t=nil, when_done=nil t ||= cursor_thread or return Redwood::reporting_thread("load messages for thread-view-mode") do num = t.size message = "Loading #{num.pluralize 'message body'}..." BufferManager.say(message) do |sid| t.each_with_index do |(m, *_), i| next unless m BufferManager.say "#{message} (#{i}/#{num})", sid if t.size > 1 m.load_from_source! end end mode = ThreadViewMode.new t, @hidden_labels, self BufferManager.spawn t.subj, mode BufferManager.draw_screen mode.jump_to_first_open if $config[:jump_to_open_message] BufferManager.draw_screen # lame TODO: make this unnecessary ## the first draw_screen is needed before topline and botline ## are set, and the second to show the cursor having moved t.remove_label :unread Index.save_thread t update_text_for_line curpos UpdateManager.relay self, :read, t.first when_done.call if when_done end end
ruby
def select t=nil, when_done=nil t ||= cursor_thread or return Redwood::reporting_thread("load messages for thread-view-mode") do num = t.size message = "Loading #{num.pluralize 'message body'}..." BufferManager.say(message) do |sid| t.each_with_index do |(m, *_), i| next unless m BufferManager.say "#{message} (#{i}/#{num})", sid if t.size > 1 m.load_from_source! end end mode = ThreadViewMode.new t, @hidden_labels, self BufferManager.spawn t.subj, mode BufferManager.draw_screen mode.jump_to_first_open if $config[:jump_to_open_message] BufferManager.draw_screen # lame TODO: make this unnecessary ## the first draw_screen is needed before topline and botline ## are set, and the second to show the cursor having moved t.remove_label :unread Index.save_thread t update_text_for_line curpos UpdateManager.relay self, :read, t.first when_done.call if when_done end end
[ "def", "select", "t", "=", "nil", ",", "when_done", "=", "nil", "t", "||=", "cursor_thread", "or", "return", "Redwood", "::", "reporting_thread", "(", "\"load messages for thread-view-mode\"", ")", "do", "num", "=", "t", ".", "size", "message", "=", "\"Loading #{num.pluralize 'message body'}...\"", "BufferManager", ".", "say", "(", "message", ")", "do", "|", "sid", "|", "t", ".", "each_with_index", "do", "|", "(", "m", ",", "*", "_", ")", ",", "i", "|", "next", "unless", "m", "BufferManager", ".", "say", "\"#{message} (#{i}/#{num})\"", ",", "sid", "if", "t", ".", "size", ">", "1", "m", ".", "load_from_source!", "end", "end", "mode", "=", "ThreadViewMode", ".", "new", "t", ",", "@hidden_labels", ",", "self", "BufferManager", ".", "spawn", "t", ".", "subj", ",", "mode", "BufferManager", ".", "draw_screen", "mode", ".", "jump_to_first_open", "if", "$config", "[", ":jump_to_open_message", "]", "BufferManager", ".", "draw_screen", "# lame TODO: make this unnecessary", "## the first draw_screen is needed before topline and botline", "## are set, and the second to show the cursor having moved", "t", ".", "remove_label", ":unread", "Index", ".", "save_thread", "t", "update_text_for_line", "curpos", "UpdateManager", ".", "relay", "self", ",", ":read", ",", "t", ".", "first", "when_done", ".", "call", "if", "when_done", "end", "end" ]
open up a thread view window
[ "open", "up", "a", "thread", "view", "window" ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L107-L135
train
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.multi_toggle_spam
def multi_toggle_spam threads undos = threads.map { |t| actually_toggle_spammed t } threads.each { |t| HookManager.run("mark-as-spam", :thread => t) } UndoManager.register "marking/unmarking #{threads.size.pluralize 'thread'} as spam", undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } } regen_text threads.each { |t| Index.save_thread t } end
ruby
def multi_toggle_spam threads undos = threads.map { |t| actually_toggle_spammed t } threads.each { |t| HookManager.run("mark-as-spam", :thread => t) } UndoManager.register "marking/unmarking #{threads.size.pluralize 'thread'} as spam", undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } } regen_text threads.each { |t| Index.save_thread t } end
[ "def", "multi_toggle_spam", "threads", "undos", "=", "threads", ".", "map", "{", "|", "t", "|", "actually_toggle_spammed", "t", "}", "threads", ".", "each", "{", "|", "t", "|", "HookManager", ".", "run", "(", "\"mark-as-spam\"", ",", ":thread", "=>", "t", ")", "}", "UndoManager", ".", "register", "\"marking/unmarking #{threads.size.pluralize 'thread'} as spam\"", ",", "undos", ",", "lambda", "{", "regen_text", "}", ",", "lambda", "{", "threads", ".", "each", "{", "|", "t", "|", "Index", ".", "save_thread", "t", "}", "}", "regen_text", "threads", ".", "each", "{", "|", "t", "|", "Index", ".", "save_thread", "t", "}", "end" ]
both spam and deleted have the curious characteristic that you always want to hide the thread after either applying or removing that label. in all thread-index-views except for label-search-results-mode, when you mark a message as spam or deleted, you want it to disappear immediately; in LSRM, you only see deleted or spam emails, and when you undelete or unspam them you also want them to disappear immediately.
[ "both", "spam", "and", "deleted", "have", "the", "curious", "characteristic", "that", "you", "always", "want", "to", "hide", "the", "thread", "after", "either", "applying", "or", "removing", "that", "label", ".", "in", "all", "thread", "-", "index", "-", "views", "except", "for", "label", "-", "search", "-", "results", "-", "mode", "when", "you", "mark", "a", "message", "as", "spam", "or", "deleted", "you", "want", "it", "to", "disappear", "immediately", ";", "in", "LSRM", "you", "only", "see", "deleted", "or", "spam", "emails", "and", "when", "you", "undelete", "or", "unspam", "them", "you", "also", "want", "them", "to", "disappear", "immediately", "." ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L474-L481
train
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.multi_toggle_deleted
def multi_toggle_deleted threads undos = threads.map { |t| actually_toggle_deleted t } UndoManager.register "deleting/undeleting #{threads.size.pluralize 'thread'}", undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } } regen_text threads.each { |t| Index.save_thread t } end
ruby
def multi_toggle_deleted threads undos = threads.map { |t| actually_toggle_deleted t } UndoManager.register "deleting/undeleting #{threads.size.pluralize 'thread'}", undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } } regen_text threads.each { |t| Index.save_thread t } end
[ "def", "multi_toggle_deleted", "threads", "undos", "=", "threads", ".", "map", "{", "|", "t", "|", "actually_toggle_deleted", "t", "}", "UndoManager", ".", "register", "\"deleting/undeleting #{threads.size.pluralize 'thread'}\"", ",", "undos", ",", "lambda", "{", "regen_text", "}", ",", "lambda", "{", "threads", ".", "each", "{", "|", "t", "|", "Index", ".", "save_thread", "t", "}", "}", "regen_text", "threads", ".", "each", "{", "|", "t", "|", "Index", ".", "save_thread", "t", "}", "end" ]
see comment for multi_toggle_spam
[ "see", "comment", "for", "multi_toggle_spam" ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L489-L495
train
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.multi_kill
def multi_kill threads UndoManager.register "killing/unkilling #{threads.size.pluralize 'threads'}" do threads.each do |t| if t.toggle_label :killed add_or_unhide t.first else hide_thread t end end.each do |t| UpdateManager.relay self, :labeled, t.first Index.save_thread t end regen_text end threads.each do |t| if t.toggle_label :killed hide_thread t else add_or_unhide t.first end end.each do |t| # send 'labeled'... this might be more specific UpdateManager.relay self, :labeled, t.first Index.save_thread t end killed, unkilled = threads.partition { |t| t.has_label? :killed }.map(&:size) BufferManager.flash "#{killed.pluralize 'thread'} killed, #{unkilled} unkilled" regen_text end
ruby
def multi_kill threads UndoManager.register "killing/unkilling #{threads.size.pluralize 'threads'}" do threads.each do |t| if t.toggle_label :killed add_or_unhide t.first else hide_thread t end end.each do |t| UpdateManager.relay self, :labeled, t.first Index.save_thread t end regen_text end threads.each do |t| if t.toggle_label :killed hide_thread t else add_or_unhide t.first end end.each do |t| # send 'labeled'... this might be more specific UpdateManager.relay self, :labeled, t.first Index.save_thread t end killed, unkilled = threads.partition { |t| t.has_label? :killed }.map(&:size) BufferManager.flash "#{killed.pluralize 'thread'} killed, #{unkilled} unkilled" regen_text end
[ "def", "multi_kill", "threads", "UndoManager", ".", "register", "\"killing/unkilling #{threads.size.pluralize 'threads'}\"", "do", "threads", ".", "each", "do", "|", "t", "|", "if", "t", ".", "toggle_label", ":killed", "add_or_unhide", "t", ".", "first", "else", "hide_thread", "t", "end", "end", ".", "each", "do", "|", "t", "|", "UpdateManager", ".", "relay", "self", ",", ":labeled", ",", "t", ".", "first", "Index", ".", "save_thread", "t", "end", "regen_text", "end", "threads", ".", "each", "do", "|", "t", "|", "if", "t", ".", "toggle_label", ":killed", "hide_thread", "t", "else", "add_or_unhide", "t", ".", "first", "end", "end", ".", "each", "do", "|", "t", "|", "# send 'labeled'... this might be more specific", "UpdateManager", ".", "relay", "self", ",", ":labeled", ",", "t", ".", "first", "Index", ".", "save_thread", "t", "end", "killed", ",", "unkilled", "=", "threads", ".", "partition", "{", "|", "t", "|", "t", ".", "has_label?", ":killed", "}", ".", "map", "(", ":size", ")", "BufferManager", ".", "flash", "\"#{killed.pluralize 'thread'} killed, #{unkilled} unkilled\"", "regen_text", "end" ]
m-m-m-m-MULTI-KILL
[ "m", "-", "m", "-", "m", "-", "m", "-", "MULTI", "-", "KILL" ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L509-L539
train
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.thread_matches?
def thread_matches? t, query t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query } end
ruby
def thread_matches? t, query t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query } end
[ "def", "thread_matches?", "t", ",", "query", "t", ".", "subj", "=~", "query", "||", "t", ".", "snippet", "=~", "query", "||", "t", ".", "participants", ".", "any?", "{", "|", "x", "|", "x", ".", "longname", "=~", "query", "}", "end" ]
used to tag threads by query. this can be made a lot more sophisticated, but for right now we'll do the obvious this.
[ "used", "to", "tag", "threads", "by", "query", ".", "this", "can", "be", "made", "a", "lot", "more", "sophisticated", "but", "for", "right", "now", "we", "ll", "do", "the", "obvious", "this", "." ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L811-L813
train
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.author_names_and_newness_for_thread
def author_names_and_newness_for_thread t, limit=nil new = {} seen = {} authors = t.map do |m, *o| next unless m && m.from new[m.from] ||= m.has_label?(:unread) next if seen[m.from] seen[m.from] = true m.from end.compact result = [] authors.each do |a| break if limit && result.size >= limit name = if AccountManager.is_account?(a) "me" elsif t.authors.size == 1 a.mediumname else a.shortname end result << [name, new[a]] end if result.size == 1 && (author_and_newness = result.assoc("me")) unless (recipients = t.participants - t.authors).empty? result = recipients.collect do |r| break if limit && result.size >= limit name = (recipients.size == 1) ? r.mediumname : r.shortname ["(#{name})", author_and_newness[1]] end end end result end
ruby
def author_names_and_newness_for_thread t, limit=nil new = {} seen = {} authors = t.map do |m, *o| next unless m && m.from new[m.from] ||= m.has_label?(:unread) next if seen[m.from] seen[m.from] = true m.from end.compact result = [] authors.each do |a| break if limit && result.size >= limit name = if AccountManager.is_account?(a) "me" elsif t.authors.size == 1 a.mediumname else a.shortname end result << [name, new[a]] end if result.size == 1 && (author_and_newness = result.assoc("me")) unless (recipients = t.participants - t.authors).empty? result = recipients.collect do |r| break if limit && result.size >= limit name = (recipients.size == 1) ? r.mediumname : r.shortname ["(#{name})", author_and_newness[1]] end end end result end
[ "def", "author_names_and_newness_for_thread", "t", ",", "limit", "=", "nil", "new", "=", "{", "}", "seen", "=", "{", "}", "authors", "=", "t", ".", "map", "do", "|", "m", ",", "*", "o", "|", "next", "unless", "m", "&&", "m", ".", "from", "new", "[", "m", ".", "from", "]", "||=", "m", ".", "has_label?", "(", ":unread", ")", "next", "if", "seen", "[", "m", ".", "from", "]", "seen", "[", "m", ".", "from", "]", "=", "true", "m", ".", "from", "end", ".", "compact", "result", "=", "[", "]", "authors", ".", "each", "do", "|", "a", "|", "break", "if", "limit", "&&", "result", ".", "size", ">=", "limit", "name", "=", "if", "AccountManager", ".", "is_account?", "(", "a", ")", "\"me\"", "elsif", "t", ".", "authors", ".", "size", "==", "1", "a", ".", "mediumname", "else", "a", ".", "shortname", "end", "result", "<<", "[", "name", ",", "new", "[", "a", "]", "]", "end", "if", "result", ".", "size", "==", "1", "&&", "(", "author_and_newness", "=", "result", ".", "assoc", "(", "\"me\"", ")", ")", "unless", "(", "recipients", "=", "t", ".", "participants", "-", "t", ".", "authors", ")", ".", "empty?", "result", "=", "recipients", ".", "collect", "do", "|", "r", "|", "break", "if", "limit", "&&", "result", ".", "size", ">=", "limit", "name", "=", "(", "recipients", ".", "size", "==", "1", ")", "?", "r", ".", "mediumname", ":", "r", ".", "shortname", "[", "\"(#{name})\"", ",", "author_and_newness", "[", "1", "]", "]", "end", "end", "end", "result", "end" ]
preserve author order from the thread
[ "preserve", "author", "order", "from", "the", "thread" ]
36f95462e3014c354c577d63a78ba030c4b84474
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L892-L928
train