code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def upgrade_reviewer_to_real(organization, role)
# First attempt to find the membership for the given organization,
# or any membership that the account is a reviewer of
membership = memberships.where({:role=>Account::REVIEWER, :organization=>organization }).first ||
memberships.where({:role=>Account::REVIEWER}).first
membership.update_attributes({:role=>role, :organization_id=>organization.id })
end | Upgrades a reviewer account to a newsroom account.
Switches their membership to the given role and makes sure the organization is correct | upgrade_reviewer_to_real | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def send_reset_request
ensure_security_key!
LifecycleMailer.reset_request(self).deliver_now
end | When a password reset request is made, send an email with a secure key to
reset the password. | send_reset_request | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def hashed_email
@hashed_email ||= Digest::MD5.hexdigest(email.downcase.gsub(/\s/, '')) if email
end | MD5 hash of processed email address, for use in Gravatar URLs. | hashed_email | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def pending?
!hashed_password && !reviewer?
end | Has this account been assigned, but never logged into, with no password set? | pending? | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def password
return false if hashed_password.nil?
@password ||= BCrypt::Password.new(hashed_password)
end | It's slo-o-o-w to compare passwords. Which is a mixed bag, but mostly good. | password | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def set_default_membership(default_membership)
raise "Membership must belong to account!" unless default_membership.account_id==self.id
self.memberships.each do | membership |
membership.update_attributes({ :default => (membership.id == default_membership.id) })
end
end | Set the default membership. Will mark the given membership as the default
and the other memberships (if any) as non-default | set_default_membership | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def canonical(options = {})
attrs = {
'id' => id,
'slug' => slug,
'email' => email,
'first_name' => first_name,
'last_name' => last_name,
'language' => language,
'document_language' => document_language,
'hashed_email' => hashed_email,
'pending' => pending?,
}
if options[:include_memberships]
attrs['memberships'] = memberships.map{ |m| m.canonical(options) }
end
if options[:include_document_counts]
attrs['public_documents'] = Document.unrestricted.where(:account_id=>id).count
attrs['private_documents'] = Document.restricted.where(:account_id => id).count
end
# all of the below should be rendered obsolete and removed.
if ( membership = options[:membership] || memberships.default.first )
attrs['organization_id'] = membership.organization_id
attrs['role'] = membership.role
end
if options[:include_organization]
attrs['organization_name'] = membership.organization.name if membership
attrs['organizations'] = organizations.map(&:canonical)
end
attrs
end | Create default organization to preserve backwards compatability. | canonical | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def user_provided_title
(title.blank? || title == 'Untitled Note') ? '' : title
end | The interface prefills the note title with "Untitled Note", so that gets
saved to the database as the note's title. In certain interfaces (e.g.,
Twitter cards) we only want to surface titles that a user actually provided. | user_provided_title | ruby | documentcloud/documentcloud | app/models/annotation.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/annotation.rb | MIT |
def contextual_url
File.join(DC.server_root, contextual_path)
end | `contextual` means "show this thing in the context of its document parent",
which right now correlates to its page-anchored version. | contextual_url | ruby | documentcloud/documentcloud | app/models/annotation.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/annotation.rb | MIT |
def transform_coordinates_to_legacy(coords)
{
top: coords[:top] + 1,
left: coords[:left] - 2,
right: coords[:right] ,
height: coords[:height] ,
width: coords[:width] - 8,
}
end | For unknown reasons, we do this | transform_coordinates_to_legacy | ruby | documentcloud/documentcloud | app/models/annotation.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/annotation.rb | MIT |
def merge(entity)
self.relevance = (self.relevance + entity.relevance) / 2.0
@split_occurrences = self.split_occurrences + entity.split_occurrences
self.occurrences = Occurrence.to_csv(@split_occurrences)
end | Merge this entity with another of the "same" entity for the same document.
Needs to happen when the pass the document's text to Calais in chunks. | merge | ruby | documentcloud/documentcloud | app/models/entity.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/entity.rb | MIT |
def pages(occurs=split_occurrences)
return [] unless textual?
super(occurs)
end | The pages on which this entity occurs within the document. | pages | ruby | documentcloud/documentcloud | app/models/entity.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/entity.rb | MIT |
def as_json(options={})
data = {
'id' => id,
'document_id' => document_id,
'date' => date.to_time.to_f.to_i
}
data['excerpts'] = excerpts(150, self.pages.limit(200) ) if options[:include_excerpts]
data
end | NB: We use "to_f.to_i" because "to_i" isn't defined for DateTime objects
that fall outside a distance of 30 bits from the regular UNIX Epoch. | as_json | ruby | documentcloud/documentcloud | app/models/entity_date.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/entity_date.rb | MIT |
def page_offset
offset - page.start_offset
end | Return this occurrence's offset relative to its page. | page_offset | ruby | documentcloud/documentcloud | app/models/occurrence.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/occurrence.rb | MIT |
def document_count
@document_count ||= self.documents.count
end | How many documents have been uploaded across the whole organization? | document_count | ruby | documentcloud/documentcloud | app/models/organization.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/organization.rb | MIT |
def admin_emails
self.accounts.admin.pluck( :email )
end | The list of all administrator emails in the organization. | admin_emails | ruby | documentcloud/documentcloud | app/models/organization.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/organization.rb | MIT |
def safe_aspect_ratio
(aspect_ratio.to_f > 0 && aspect_ratio) || (document.calculate_aspect_ratios && 8.5/11)
end | We only recently started calculating aspect ratios, and haven't
back-calculated all aspect ratios. Return one if we have; otherwise, queue
up a document process action to calculate the ratios and temporarily return
the most common size, 8.5x11. | safe_aspect_ratio | ruby | documentcloud/documentcloud | app/models/page.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/page.rb | MIT |
def inverted_aspect_ratio
1 / safe_aspect_ratio
end | Normal aspect ratio is `width / height`, but for the purposes of the
`padding-bottom` responsive trick, we need `height / width`. | inverted_aspect_ratio | ruby | documentcloud/documentcloud | app/models/page.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/page.rb | MIT |
def track_text_changes
return true unless text_changed?
self.text = strip_tags(text)
DC::Store::AssetStore.new.save_page_text(self.document, self.page_number, self.text, access)
@text_changed = true
end | Make sure that HTML never gets written into the plain text contents.
TODO: Should we go back to Calais and blow away entities for little edits? | track_text_changes | ruby | documentcloud/documentcloud | app/models/page.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/page.rb | MIT |
def queue
# If a Document is associated with this ProcessingJob, determine
# whether the Document is available to be worked on, and if it's not
# use ActiveRecord's error system to indicate it's unavailability.
#if document and document.has_running_jobs?
# errors.add(:document, "This document is already being processed") and (return false)
#
# # in future we'll actually lock the document
# # Lock the document & contact CloudCrowd to start the job
# #document.update :status => UNAVAILABLE
#end
begin
# Note the job id once CloudCrowd has recorded the job.
@response = RestClient.post(ProcessingJob.endpoint, {:job => CloudCrowdSerializer.new(self).to_json})
@remote_job = JSON.parse @response.body
self.cloud_crowd_id = @remote_job['id']
# We've collected all the info we need, so
save # it and retain the lock on the document.
rescue Errno::ECONNREFUSED, RestClient::Exception => error
LifecycleMailer.exception_notification(error).deliver_now
# In the event of an error while communicating with CloudCrowd, unlock the document.
self.update_attributes :complete => true
#document.update :status => AVAILABLE
raise error
end
end | Validate and initiate this job with CloudCrowd. | queue | ruby | documentcloud/documentcloud | app/models/processing_job.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/processing_job.rb | MIT |
def status
(@remote_job || fetch_job).merge(attributes)
end | Return the JSON-ready Job status. | status | ruby | documentcloud/documentcloud | app/models/processing_job.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/processing_job.rb | MIT |
def as_json(opts={})
{ 'id' => id,
'title' => title,
'status' => 'loading'
}
end | The default JSON of a processing job is just enough to get it polling for
updates again. | as_json | ruby | documentcloud/documentcloud | app/models/processing_job.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/processing_job.rb | MIT |
def annotation_count(account=nil)
account ||= self.account
@annotation_count ||= Annotation.count_by_sql <<-EOS
select count(*) from annotations
inner join project_memberships on project_memberships.document_id = annotations.document_id
where project_memberships.project_id = #{id}
and (annotations.access in (#{PUBLIC}, #{EXCLUSIVE}) or
annotations.access = #{PRIVATE} and annotations.account_id = #{account.id})
EOS
end | How many annotations belong to documents belonging to this project?
How many of those annotations are accessible to a given account?
TODO: incorporate PREMODERATED and POSTMODERATED comments into counts | annotation_count | ruby | documentcloud/documentcloud | app/models/project.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/project.rb | MIT |
def canonical(options={})
data = {
'id' => id,
'title' => title,
'description' => description,
'public_url' => public_url
}
if options.fetch(:include_document_ids, true)
data['document_ids'] = canonical_document_ids
else
data['document_count'] = project_memberships.count
end
data
end | Options:
:include_document_ids: if set and false, add a 'document_count' Integer.
Otherwise, add a 'document_ids' Array. | canonical | ruby | documentcloud/documentcloud | app/models/project.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/project.rb | MIT |
def canonical
{'title' => title, 'page' => page_number}
end | The canonical JSON representation of a section. | canonical | ruby | documentcloud/documentcloud | app/models/section.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/section.rb | MIT |
def boot_instance(options)
options = DEFAULT_BOOT_OPTIONS.merge(options)
ssh_config = {
'CheckHostIP' => 'no',
'StrictHostKeyChecking' => 'no',
'UserKnownHostsFile' => '/dev/null',
'User' => 'ubuntu',
'IdentityFile' => "#{Rails.root}/secrets/keys/documentcloud.pem"
}
File.chmod(0600, ssh_config['IdentityFile'])
new_instance = ec2.instances.create({
:image_id => options[:ami],
:count => 1,
:security_groups => ['default'],
:key_name => 'DocumentCloud 2014-04-12',
:instance_type => options[:type],
:availability_zone => DC::CONFIG['aws_zone']
})
if ( name = options[:name] )
new_instance.tag('Name', value: name )
end
# wait until instance is running and get the public dns name
while :pending == new_instance.status
sleep 2
Rails.logger.info "waiting for instance #{new_instance.instance_id} state to become 'running'"
end
# wait until the instance is running sshd
ssh_options = ssh_config.collect {|k,v| "-o #{k}=#{v}"}.join " "
while true do
sleep 2
break if system "ssh -o ConnectTimeout=10 #{ssh_options} #{new_instance.dns_name} exit 0 2>/dev/null"
Rails.logger.info "waiting for instance #{new_instance.instance_id} / #{new_instance.dns_name} to start sshd "
end
# configure new instance with ssh key to access github
system "ssh #{ssh_options} #{new_instance.dns_name} 'test -e .ssh/id_dsa && exit 0; mkdir -p .ssh; while read line; do echo $line; done > .ssh/id_dsa; chmod 0600 .ssh/id_dsa' < #{Rails.root}/secrets/keys/github.pem"
# configure new instance
unless options[:scripts].empty?
options[:scripts].each do |script|
system "ssh #{ssh_options} #{new_instance.dns_name} sudo bash -x < #{script}"
end
end
Rails.logger.info "ssh #{ssh_options} #{new_instance.dns_name}"
return new_instance
end | Boot a new instance, given `ami`, `type`, and `scripts` options. | boot_instance | ruby | documentcloud/documentcloud | lib/dc/aws.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/aws.rb | MIT |
def execute_on_hosts(script, hosts)
hosts.each do |host|
@threads.push(Thread.new{
command = "ssh #{ssh_options} #{host} \"bash -ls\" <<SCRIPT\n#{script}\nSCRIPT"
puts "SSHing to #{host}:\n" + `#{command}`
})
end
@threads.each{ |t| t.join }
return hosts
end | A wrangler will execute a shell script across a a list of hosts | execute_on_hosts | ruby | documentcloud/documentcloud | lib/dc/cloud_crowd.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/cloud_crowd.rb | MIT |
def get_hosts_named(pattern=DEFAULT_WORKER_MATCHER)
ec2 = AWS::EC2.new
puts "Fetching worker host names"
instances = ec2.instances.select{ |i| i.status == :running && i.tags["Name"] =~ pattern }
return instances.map{ |i| i.dns_name }
end | this method should be abstracted or generalized to take a block, or both.
For DocumentCloud's purposes, we're running on Amazon & name extra nodes "workers"
so we fetch the list of machines using a regexp. | get_hosts_named | ruby | documentcloud/documentcloud | lib/dc/cloud_crowd.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/cloud_crowd.rb | MIT |
def launch_nodes(options={})
DC::AWS.new.launch_instances(options) do |instances|
execute_on_hosts(script_contents("startup"), instances.map(&:dns_name))
end
end | Start new ec2 instance(s) and provision them as worker nodes.
Options:
:count - Number of nodes to start, defaults to 1
:node_name - What to name the nodes once they're booted, defaults to "worker" | launch_nodes | ruby | documentcloud/documentcloud | lib/dc/cloud_crowd.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/cloud_crowd.rb | MIT |
def safe_unescape(s)
unless s.nil?
return CGI.unescape_html(s)
end
s
end | Unescape HTML in a safe fashion, allowing nil values to pass through | safe_unescape | ruby | documentcloud/documentcloud | lib/dc/sanitized.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/sanitized.rb | MIT |
def text_attr(*attrs)
attrs.each do |att|
class_eval "def #{att}=(val); self[:#{att}] = safe_unescape(strip(val)); end"
end
end | Text attributes are stripped of HTML before they are saved. | text_attr | ruby | documentcloud/documentcloud | lib/dc/sanitized.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/sanitized.rb | MIT |
def html_attr(*attrs)
options = attrs.extract_options!.reverse_merge({
:level => :super_relaxed
})
attrs.each do |att|
class_eval "def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end"
end
end | HTML attributes are sanitized of malicious HTML before being saved.
Accepts a list of attribute names, with optional level specifiied at end.
If not specified, the level defaults to :super_relaxed
html_attr :sanitized_attr, :another_sanitized_attr, :level=>:basic | html_attr | ruby | documentcloud/documentcloud | lib/dc/sanitized.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/sanitized.rb | MIT |
def initialize(file, attributes)
@file, @attributes = file, attributes
raise "Documents must have a file and title to be uploaded" unless @file && @attributes[:title]
end | Initialize the uploader with the document file, it's title, and the
optional access, source, and description... | initialize | ruby | documentcloud/documentcloud | lib/dc/uploader.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/uploader.rb | MIT |
def initialize(resource, embed_config={}, options={})
raise NotImplementedError
end | Embed presenters accept
a hash representing a resource,
configuration which specifies how the embed markup/data will be generated
and a set of options specifying how the presenter will behave | initialize | ruby | documentcloud/documentcloud | lib/dc/embed/base.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb | MIT |
def define_attributes
@attributes = {}
@attribute_map = {}
yield # to the user defined block for further instruction
@keys = @attributes.keys.freeze
@attribute_map.freeze
@attributes.freeze
end | set up the hashes we'll use to
keep track of the whitelist of attributes
and their types | define_attributes | ruby | documentcloud/documentcloud | lib/dc/embed/base.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb | MIT |
def coerce(value, field_name)
type = self.class.attributes[field_name]
case type
when :boolean
case
when (value.kind_of? TrueClass or value.kind_of? FalseClass); then value
when value == "true"; then true
when (value || '').match(/no|false/); then false # For Overview
else; value
end
when :number
case
when value.kind_of?(Numeric); then value
when value =~ /\A[+-]?\d+\Z/; then value.to_i
when value =~ /\A[+-]?\d+\.\d+\Z/; then value.to_f
else; value
end
when :string
value.to_s unless value.nil?
else
raise ArgumentError, "#{type} isn't supported as a configuration key type."
end
end | coerce values according to the type of their field | coerce | ruby | documentcloud/documentcloud | lib/dc/embed/base.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb | MIT |
def initialize(data:{}, options:{map_keys: true})
@options = options
self.class.keys.each{ |attribute| self[attribute] = data[attribute] }
end | When initializing search the input arguments for fields which
this configuration class accepts | initialize | ruby | documentcloud/documentcloud | lib/dc/embed/base.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/base.rb | MIT |
def calculate_dimensions
embed_dimensions = @note.embed_dimensions
@dimensions = {
height: @embed_config[:maxheight] || (@embed_config[:maxwidth] ? (@embed_config[:maxwidth] / embed_dimensions[:aspect_ratio]).round : embed_dimensions[:height_pixel]),
width: @embed_config[:maxwidth] || (@embed_config[:maxheight] ? (@embed_config[:maxheight] * embed_dimensions[:aspect_ratio]).round : embed_dimensions[:width_pixel])
}
end | These won't be accurate, since this is the note image area only. Still,
gives the oEmbed response *some* sense of the scale and aspect ratio. | calculate_dimensions | ruby | documentcloud/documentcloud | lib/dc/embed/note.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/note.rb | MIT |
def code
[content_markup, bootstrap_markup].join("\n").squish
end | Page embed uses a noscript-style enhancer, which prefers content markup
before bootstrap markup | code | ruby | documentcloud/documentcloud | lib/dc/embed/page.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/embed/page.rb | MIT |
def fetch_rdf(text)
rdfs = []
begin
rdfs = split_text(text).map do |chunk|
fetch_rdf_from_calais(chunk)
end
rescue Exception => e
LifecycleMailer.exception_notification(e).deliver_now
end
rdfs
end | Fetch the RDF from OpenCalais, splitting it into chunks small enough
for Calais to swallow. Run the chunks in parallel. | fetch_rdf | ruby | documentcloud/documentcloud | lib/dc/import/calais_fetcher.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/calais_fetcher.rb | MIT |
def extract_dates( text )
@dates = {}
scan_for(DATE_MATCH, text)
reject_outliers
@dates.values
end | Extract the unique dates within the text. | extract_dates | ruby | documentcloud/documentcloud | lib/dc/import/date_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb | MIT |
def scan_for(matcher, text)
scanner = TextScanner.new(text)
scanner.scan(matcher) do |match, offset, length|
next unless date = to_date(match)
@dates[date] ||= {:date => date, :occurrences => []}
@dates[date][:occurrences].push(Occurrence.new(offset, length))
end
end | Scans for the regex within the text, saving valid dates and occurrences. | scan_for | ruby | documentcloud/documentcloud | lib/dc/import/date_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb | MIT |
def reject_outliers
dates = @dates.values.map {|d| d[:date] }
count = dates.length
return true if count < 10 # Not enough dates for detection.
nums = dates.map {|d| d.to_time.to_f.to_i }
mean = nums.inject {|a, b| a + b } / count.to_f
deviation = Math.sqrt(nums.inject(0){|sum, n| sum + (n - mean) ** 2 } / count.to_f)
allowed = ((mean - 3.0 * deviation)..(mean + 3.0 * deviation))
@dates.delete_if {|date, hash| !allowed.include?(date.to_time.to_f) }
end | Ignoring dates that are outside of three standard deviations ...
they're probably errors. | reject_outliers | ruby | documentcloud/documentcloud | lib/dc/import/date_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb | MIT |
def to_date(string)
list = string.split(SPLITTER)
return nil unless valid_year?(list.first) || valid_year?(list.last)
if @american_format # US format dates need to have month and day swapped for Date.parse
string.sub!( AMERICAN_REGEX ){|m| "#$3-#$1-#$2"}
end
date = Date.parse(string.gsub(SEP_REGEX, '/'), true) rescue nil
date ||= Date.parse(string.gsub(SEP_REGEX, '-'), true) rescue nil
return nil if date && (date.year <= 0 || date.year >= 2100)
date
end | ActiveRecord's to_time only supports two-digit years up to 2038.
(because the UNIX epoch overflows 30 bits at that point, probably).
For now, let's ignore dates without centuries,
and dates that are too far into the past or future. | to_date | ruby | documentcloud/documentcloud | lib/dc/import/date_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/date_extractor.rb | MIT |
def extract(document, text)
@entities = {}
if chunks = CalaisFetcher.new.fetch_rdf(text)
chunks.each_with_index do |chunk, i|
next unless chunk
extract_information(document, chunks.first) if document.calais_id.blank?
extract_entities(document, chunk, i)
end
document.entities = @entities.values
document.save
else
# push an entity extraction job onto the queue.
end
end | Public API: Pass in a document, either with full_text or rdf already
attached. | extract | ruby | documentcloud/documentcloud | lib/dc/import/entity_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/entity_extractor.rb | MIT |
def extract_information(document, calais)
if calais and calais.raw and calais.raw.body and calais.raw.body.doc
info_elements = calais.raw.body.doc.info
document.title = info_elements.docTitle unless document.titled?
document.language ||= 'en' # TODO: Convert calais.language into an ISO language code.
document.publication_date ||= info_elements.docDate
document.calais_id = File.basename(info_elements.docId) # Match string of characters after the last forward slash to the end of the url to get calais id. example: http://d.opencalais.com/dochash-1/c4d2ae6a-5049-34eb-992c-67881899bccd
end
end | Pull out all of the standard, top-level entities, and add it to our
document if it hasn't already been set. | extract_information | ruby | documentcloud/documentcloud | lib/dc/import/entity_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/entity_extractor.rb | MIT |
def extract_entities(document, calais, chunk_number)
offset = chunk_number * MAX_TEXT_SIZE
calais.entities.each do |entity|
kind = Entity.normalize_kind(entity[:type])
value = entity[:name]
next unless kind && value
value = Entity.normalize_value(value)
next if kind == :phone && Validators::PHONE !~ value
next if kind == :email && Validators::EMAIL !~ value
occurrences = entity[:matches].map do |instance|
Occurrence.new(instance[:offset] + offset, instance[:length])
end
model = Entity.new(
:value => value,
:kind => kind.to_s,
:relevance => entity[:score],
:document => document,
:occurrences => Occurrence.to_csv(occurrences),
:calais_id => File.basename(entity[:guid]) # Match string of characters after the last forward slash to the end of the url to get calais id. example: http://d.opencalais.com/comphash-1/7f9f8e5d-782c-357a-b6f3-7a5321f92e13
)
if previous = @entities[model.calais_id]
previous.merge(model)
else
@entities[model.calais_id] = model
end
end
end | Extract the entities that Calais discovers in the document, along with
the positions where they occur. | extract_entities | ruby | documentcloud/documentcloud | lib/dc/import/entity_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/entity_extractor.rb | MIT |
def ensure_pdf(file, filename=nil)
Dir.mktmpdir do |temp_dir|
path = file.path
original_filename = filename || file.original_filename
ext = File.extname(original_filename).downcase
name = File.basename(original_filename, File.extname(original_filename)).gsub(/[^a-zA-Z0-9_\-.]/, '-').gsub(/-+/, '-') + ext
if ext == ".pdf" && File.extname(path) != ".pdf"
new_path = File.join(temp_dir, name)
FileUtils.mv(path, new_path)
path = new_path
end
return yield(path) if ext == ".pdf"
begin
doc = File.join(temp_dir, name)
FileUtils.cp(path, doc)
Docsplit.extract_pdf(doc, :output => temp_dir)
yield(File.join(temp_dir, File.basename(name, ext) + '.pdf'))
rescue Exception => e
LifecycleMailer.exception_notification(e).deliver_now
Rails.logger.error("PDF Conversion Failed: " + e.message + "\n" + e.backtrace.join("\n"))
yield path
end
end
end | Make sure we're dealing with a PDF. If not, it needs to be
converted first. Yields the path to the converted document to a block. | ensure_pdf | ruby | documentcloud/documentcloud | lib/dc/import/pdf_wrangler.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/pdf_wrangler.rb | MIT |
def archive(pages, batch_size=nil)
batch_size ||= DEFAULT_BATCH_SIZE
batches = (pages.length / batch_size.to_f).ceil
batches.times do |batch_num|
tar_path = "#{sprintf('%05d', batch_num)}.tar"
batch_pages = pages[batch_num*batch_size...(batch_num + 1)*batch_size]
`tar -czf #{tar_path} #{batch_pages.join(' ')} 2>&1`
end
Dir["*.tar"]
end | Archive a list of PDF pages into TAR archives, grouped by batch_size. | archive | ruby | documentcloud/documentcloud | lib/dc/import/pdf_wrangler.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/pdf_wrangler.rb | MIT |
def extract_phone_numbers(text)
@numbers = {}
scanner = TextScanner.new(text)
scanner.scan(PHONE_MATCHER) do |match, offset, length|
next unless number = to_phone_number(match)
@numbers[number] ||= {:number => number, :occurrences => []}
@numbers[number][:occurrences].push(Occurrence.new(offset, length))
end
@numbers.values
end | Extracts the unique phone numbers within the text. | extract_phone_numbers | ruby | documentcloud/documentcloud | lib/dc/import/phone_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/phone_extractor.rb | MIT |
def to_phone_number(number)
string, area, trunk, rest, a, b, ext = *number.match(PHONE_MATCHER)
number = "(#{area}) #{trunk}-#{rest}"
number += " x#{ext}" unless ext.blank?
number
end | Converts the any-format number into the canonical (xxx) xxx-xxxx format. | to_phone_number | ruby | documentcloud/documentcloud | lib/dc/import/phone_extractor.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/phone_extractor.rb | MIT |
def initialize(text)
@text = text
@scanner = StringScanner.new(@text)
end | Initialize the **TextScanner** with a string of text. | initialize | ruby | documentcloud/documentcloud | lib/dc/import/text_scanner.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/text_scanner.rb | MIT |
def scan(regex)
while @scanner.scan_until(regex)
match = @scanner.matched
position = @scanner.charpos - match.length
yield match, position, match.length
end
end | Matches a given **regex** to all of its occurrences within the **text**,
yielding to the block with the matched text, the character offset
and character length of the match. | scan | ruby | documentcloud/documentcloud | lib/dc/import/text_scanner.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/import/text_scanner.rb | MIT |
def parse(query_string='')
@text, @access = nil, nil
@fields, @accounts, @groups, @projects, @project_ids, @doc_ids, @attributes, @filters, @data =
[], [], [], [], [], [], [], [], []
fields = query_string.scan(Matchers::FIELD).map {|m| [m[0], m[3]] }
search_text = query_string.gsub(Matchers::FIELD, '').squeeze(' ').strip
@text = search_text.present? ? search_text : nil
process_fields_and_projects(fields)
Query.new(:text => @text, :fields => @fields, :projects => @projects,
:accounts => @accounts, :groups => @groups, :project_ids => @project_ids,
:doc_ids => @doc_ids, :attributes => @attributes, :access => @access,
:filters => @filters, :data => @data)
end | Parse a raw query_string, returning a DC::Search::Query that knows
about the text, fields, projects, and attributes it's composed of. | parse | ruby | documentcloud/documentcloud | lib/dc/search/parser.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb | MIT |
def process_fields_and_projects(fields)
fields.each do |pair|
type = pair.first.gsub(/(^['"]|['"]$)/, '')
value = pair.last.gsub(/(^['"]|['"]$)/, '')
case type.downcase
when 'account' then @accounts << value.to_i
when 'group' then @groups << value.downcase
when 'filter' then @filters << value.downcase.to_sym
when 'access' then @access = ACCESS_MAP[value.strip.to_sym]
when 'project' then @projects << value
when 'projectid' then @project_ids << value.to_i
when 'document' then @doc_ids << value.to_i
else
process_field(type, value)
end
end
end | Extract the portions of the query that are fields, attributes,
and projects. | process_fields_and_projects | ruby | documentcloud/documentcloud | lib/dc/search/parser.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb | MIT |
def process_field(kind, value)
field = Field.new(match_kind(kind), value.strip)
return @attributes << field if field.attribute?
return @fields << field if field.entity?
return @data << field
end | Convert an individual field or attribute search into a DC::Search::Field. | process_field | ruby | documentcloud/documentcloud | lib/dc/search/parser.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb | MIT |
def match_kind(kind)
DC::VALID_KINDS.detect {|s| s.match(Regexp.new(kind.downcase)) } || kind
end | Convert a field kind string into its canonical form, by searching
through all the valid kinds for a match. | match_kind | ruby | documentcloud/documentcloud | lib/dc/search/parser.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/parser.rb | MIT |
def initialize(opts={})
@text = opts[:text]
@page = opts[:page].to_i
@page = 1 unless @page > 0
@access = opts[:access]
@fields = opts[:fields] || []
@accounts = opts[:accounts] || []
@groups = opts[:groups] || []
@projects = opts[:projects] || []
@project_ids = opts[:project_ids] || []
@doc_ids = opts[:doc_ids] || []
@attributes = opts[:attributes] || []
@filters = opts[:filters] || []
@data = opts[:data] || []
@from, @to, @total = nil, nil, nil
@account, @organization = nil, nil
@data_groups = @data.group_by {|datum| datum.kind }
@per_page = DEFAULT_PER_PAGE
@order = DEFAULT_ORDER
end | Queries are created by the Search::Parser, which sets them up with the
appropriate attributes. | initialize | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def generate_search
build_text if has_text?
build_fields if has_fields?
build_data if has_data?
build_accounts if has_accounts?
build_groups if has_groups?
build_project_ids if has_project_ids?
build_projects if has_projects?
build_doc_ids if has_doc_ids?
build_attributes if has_attributes?
build_filters if has_filters?
# build_facets if @include_facets
build_access unless @unrestricted
end | Generate all of the SQL, including conditions and joins, that is needed
to run the query. | generate_search | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def run(o={})
@account, @organization, @unrestricted = o[:account], o[:organization], o[:unrestricted]
@exclude_documents = o[:exclude_documents]
needs_solr? ? run_solr : run_database
populate_annotation_counts
populate_mentions o[:mentions].to_i if o[:mentions]
self
end | Runs (at most) two queries -- one to count the total number of results
that match the search, and one that retrieves the documents or notes
for the current page. | run | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def needs_solr?
@needs_solr ||= (has_text? || has_fields? || has_attributes?) ||
@data_groups.any? {|kind, list| list.length > 1 }
end | Does this query require the Solr index to run? | needs_solr? | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def populate_mentions(mentions)
raise "Invalid number of mentions" unless mentions > 0 && mentions <= 10
return false unless has_text? and has_results?
@results.each do |doc|
mention_data = Page.mentions(doc.id, @text, mentions)
doc.mentions = mention_data[:mentions]
doc.total_mentions = mention_data[:total]
end
end | If we've got a full text search with results, we can get Postgres to
generate the text mentions for our search results. | populate_mentions | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def populate_annotation_counts
return false unless has_results?
Document.populate_annotation_counts(@account, @results)
end | Stash the number of notes per-document on the document models. | populate_annotation_counts | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def as_json(opts={})
{ 'text' => @text,
'page' => @page,
'from' => @from,
'to' => @to,
'total' => @total,
'fields' => @fields,
'projects' => @projects,
'accounts' => @accounts,
'groups' => @groups,
'project_ids' => @project_ids,
'doc_ids' => @doc_ids,
'attributes' => @attributes,
'data' => @data.map {|f| [f.kind, f.value] }
}
end | # Return a hash of facets.
def facets
return {} unless @include_facets
@solr.facets.inject({}) do |hash, facet|
hash[facet.field_name] = facet.rows.map {|row| {:value => row.value, :count => row.count}}
hash
end
end
The JSON representation of a query contains all the structured aspects
of the search. | as_json | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def run_solr
@solr = Sunspot.new_search(Document)
generate_search
build_pagination
@solr.execute
@total = @solr.total
@results = @solr.results
end | Run the search, using the Solr index. | run_solr | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_pagination
page = @page
size = @per_page
order = @order.to_sym
direction = [:created_at, :score, :page_count, :hit_count].include?(order) ? :desc : :asc
pagination = {:page => page, :per_page => size}
pagination = EMPTY_PAGINATION if @exclude_documents
@solr.build do
order_by order, direction
order_by :created_at, :desc if order != :created_at
paginate pagination
data_accessor_for(Document).include = [:organization, :account]
end
end | Construct the correct pagination for the current query. | build_pagination | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_text
text = @text
@solr.build do
fulltext text
end
end | Build the Solr needed to run a full-text search. Hits the title,
the text content, the entities, etc. | build_text | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_fields
fields = @fields
@solr.build do
fields.each do |field|
fulltext field.value do
fields field.kind
end
end
end
end | Generate the Solr to search across the fielded metadata. | build_fields | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_projects
return unless @account
project_ids = Project.accessible(@account).where(:title => @projects).pluck(:id)
if project_ids.present?
@populated_projects = true
else
project_ids = [-1]
end
@project_ids = project_ids
build_project_ids
end | Lookup projects by title, and delegate to `build_project_ids`. | build_projects | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_project_ids
ids = @project_ids
if needs_solr?
@solr.build do
with :project_ids, ids
end
else
@sql << 'projects.id in (?)'
@interpolations << @project_ids
@joins << 'inner join project_memberships ON documents.id = project_memberships.document_id
inner join projects on project_memberships.project_id = projects.id'
end
end | Generate the Solr or SQL to restrict the search to specific projects. | build_project_ids | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_doc_ids
ids = @doc_ids
if needs_solr?
@solr.build do
with :id, ids
end
else
@sql << 'documents.id in (?)'
@interpolations << ids
end
end | Generate the Solr or SQL to restrict the search to specific documents. | build_doc_ids | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_accounts
ids = @accounts
if needs_solr?
@solr.build do
with :account_id, ids
end
else
@sql << 'documents.account_id in (?)'
@interpolations << ids
end
end | Generate the Solr or SQL to restrict the search to specific acounts. | build_accounts | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_groups
ids = Organization.where(:slug => @groups).pluck(:id)
if needs_solr?
@solr.build do
with :organization_id, ids
end
else
@sql << 'documents.organization_id in (?)'
@interpolations << ids
end
end | Generate the Solr or SQL to restrict the search to specific organizations. | build_groups | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_attributes
@attributes.each do |field|
@solr.build do
fulltext field.value do
fields field.kind
end
end
end
end | Generate the Solr to match document attributes. | build_attributes | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_data
data = @data
groups = @data_groups
if needs_solr?
@solr.build do
dynamic :data do
groups.each do |kind, data|
any_of do
data.each do |datum|
if datum.value == '*'
without datum.kind, nil
elsif datum.value == '!'
with datum.kind, nil
else
with datum.kind, datum.value
end
end
end
end
end
end
else
hash = {}
data.each do |datum|
if datum.value == '*'
@sql << 'defined(docdata.data, ?)'
@interpolations << datum.kind
elsif datum.value == '!'
@sql << '(docdata.data -> ?) is null'
@interpolations << datum.kind
else
@sql << '(docdata.data -> ?) LIKE ?'
@interpolations += [datum.kind, datum.value.gsub('*', '%')]
end
end
@joins << 'inner join docdata ON documents.id = docdata.document_id'
end
end | Generate the Solr or SQL to match user-data queries. If the value
is "*", assume that any document that contains the key will do. | build_data | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_filters
@filters.each do |filter|
case filter
when :annotated
if needs_solr?
# NB: Solr "greater_than" is actually >=
@solr.build { with(:public_note_count).greater_than(1) }
else
@sql << 'documents.public_note_count > 0'
end
when :popular
@order = :hit_count
if needs_solr?
@solr.build { with(:hit_count).greater_than(Document::MINIMUM_POPULAR) }
else
@sql << 'documents.hit_count > ?'
@interpolations << [Document::MINIMUM_POPULAR]
end
when :published
if needs_solr?
@solr.build { with :published, true }
else
@sql << 'documents.access in (?) and (documents.remote_url is not null or documents.detected_remote_url is not null)'
@interpolations << PUBLIC_LEVELS
end
when :unpublished
if needs_solr?
@solr.build { with :published, false }
else
@sql << 'documents.remote_url is null and documents.detected_remote_url is null'
end
when :restricted
if needs_solr?
@solr.build { with :access, [PRIVATE, ORGANIZATION, PENDING, INVISIBLE, ERROR, DELETED, EXCLUSIVE] }
else
@sql << 'documents.access in (?)'
@interpolations << [PRIVATE, ORGANIZATION, PENDING, INVISIBLE, ERROR, DELETED, EXCLUSIVE]
end
end
end
end | Add facet results to the Solr search, if requested.
def build_facets
api = @include_facets == :api
specific = @facet
@solr.build do
if specific
args = [specific.to_sym, FACET_OPTIONS[:specific]]
else
args = DC::ENTITY_KINDS + [FACET_OPTIONS[api ? :api : :all]]
end
facet(*args)
end
end
Filter documents along certain "interesting axes". | build_filters | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def build_access
@proxy = Document.accessible(@account, @organization) unless needs_solr?
if has_access?
access = @access
if needs_solr?
@solr.build do
with :access, access
end
else
@sql << 'documents.access = ?'
@interpolations << access
end
end
return unless needs_solr?
return if @populated_projects
account, organization = @account, @organization
accessible_project_ids = has_projects? || has_project_ids? ? [] : (account && account.accessible_project_ids)
@solr.build do
any_of do
with :access, PUBLIC_LEVELS
if account
all_of do
with :access, [PRIVATE, PENDING, ERROR, ORGANIZATION, EXCLUSIVE]
with :account_id, account.id
end
end
if organization && account && !account.freelancer?
all_of do
with :access, [ORGANIZATION, EXCLUSIVE]
with :organization_id, organization.id
end
end
if accessible_project_ids.present?
with :project_ids, accessible_project_ids
end
end
end
end | Restrict accessible documents for a given account/organzation.
Either the document itself is public, or it belongs to us, or it belongs to
our organization and we're allowed to see it, or if it belongs to a
project that's been shared with us, or it belongs to a project that
*hasn't* been shared with us, but is public. | build_access | ruby | documentcloud/documentcloud | lib/dc/search/query.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/search/query.rb | MIT |
def set_access(document, access)
save_permissions(document.pdf_path, access)
save_permissions(document.full_text_path, access)
document.pages.each do |page|
save_permissions(document.page_text_path(page.page_number), access)
Page::IMAGE_SIZES.keys.each do |size|
save_permissions(document.page_image_path(page.page_number, size), access)
end
end
true
end | This is going to be *extremely* expensive. We can thread it, but
there must be a better way somehow. (running in the background for now) | set_access | ruby | documentcloud/documentcloud | lib/dc/store/aws_s3_store.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb | MIT |
def copy_assets(source, destination, access)
[:copy_pdf, :copy_images, :copy_text].each do |task|
send(task, source, destination, access)
end
true
end | Duplicate all of the assets from one document over to another. | copy_assets | ruby | documentcloud/documentcloud | lib/dc/store/aws_s3_store.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb | MIT |
def validate_assets(document)
invalid = []
1.upto(document.page_count) do |pg|
text_path = document.page_text_path(pg)
invalid << text_path unless bucket.objects[text_path].exists?
Page::IMAGE_SIZES.keys.each do |size|
image_path = document.page_image_path(pg, size)
invalid << image_path unless bucket.objects[image_path].exists?
end
end
invalid
end | This is a potentially expensive (as in $$) method since S3 charges by the request
returns an array of paths that should exist in the S3 bucket but do not | validate_assets | ruby | documentcloud/documentcloud | lib/dc/store/aws_s3_store.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb | MIT |
def save_file(contents, s3_path, access, opts={})
destination = bucket.objects[s3_path]
options = opts.merge(:acl => ACCESS_TO_ACL[access], :content_type => content_type(s3_path))
destination.write(contents, options)
destination.public_url({ :secure => Thread.current[:ssl] }).to_s
end | Saves a local file to a location on S3, and returns the public URL.
Set the expires headers for a year, if the file is an image -- text,
HTML and JSON may change. | save_file | ruby | documentcloud/documentcloud | lib/dc/store/aws_s3_store.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/aws_s3_store.rb | MIT |
def split_occurrences
@split_occurrences ||= Occurrence.from_csv(self.occurrences, self)
end | Instead of having a separate table for occurrences, we serialize them to
a CSV format on each Entity. Deserializes. | split_occurrences | ruby | documentcloud/documentcloud | lib/dc/store/entity_resource.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/entity_resource.rb | MIT |
def pages( occurs=split_occurrences )
conds = occurs.map do |occur|
"(start_offset <= #{occur.offset} and end_offset > #{occur.offset})"
end
document.pages.where( conds.join(' or ') )
end | The pages on which this entity occurs within the document. | pages | ruby | documentcloud/documentcloud | lib/dc/store/entity_resource.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/entity_resource.rb | MIT |
def copy_assets(source, destination, access)
[:copy_pdf, :copy_images, :copy_text].each do |task|
send(task, source, destination, access)
end
true
end | Duplicate all of the assets from one document over to another. | copy_assets | ruby | documentcloud/documentcloud | lib/dc/store/file_system_store.rb | https://github.com/documentcloud/documentcloud/blob/master/lib/dc/store/file_system_store.rb | MIT |
def assert_working_relations( model, relations )
failed = []
relations.each do | name |
begin
model.send( name )
rescue Exception => e
failed << "#{name} - #{e}"
end
end
if failed.empty?
assert true
else
assert false, failed.join('; ')
end
end | Add more helper methods to be used by all tests here... | assert_working_relations | ruby | documentcloud/documentcloud | test/test_helper.rb | https://github.com/documentcloud/documentcloud/blob/master/test/test_helper.rb | MIT |
def zip_from_response( response )
Tempfile.open( 'testzip.zip', :encoding=>'binary' ) do | tf |
tf.write response.body
tf.flush
File.open( tf.path ) do | zip_file |
Zip::File.open( zip_file ) do | zf |
yield zf
end
end
end
end | RubyZip has a seemingly convenient Zip::ZipFile.open_buffer method - too bad it's totally borked
Various internal methods want the String passed in to have a path, monkey patching that in didn't work either
I would report a bug/pull request on it, but looks like they're in the middle of a pretty major re-write
Plus it doesn't like passing a Tempfile, since it's not a direct instance of IO (it uses DelegateClass) | zip_from_response | ruby | documentcloud/documentcloud | test/controllers/download_controller_test.rb | https://github.com/documentcloud/documentcloud/blob/master/test/controllers/download_controller_test.rb | MIT |
def test_permission_to_review
assert_difference ->{ActionMailer::Base.deliveries.count}, 1 do
LifecycleMailer.permission_to_review(doc).deliver_now
end
end | Email the owner of a document which is having difficulty processing | test_permission_to_review | ruby | documentcloud/documentcloud | test/mailers/lifecycle_mailer_test.rb | https://github.com/documentcloud/documentcloud/blob/master/test/mailers/lifecycle_mailer_test.rb | MIT |
def post_params
params.require(:post).permit(:title, :content, :copyright, clips_attributes: [ :id, :image, :_destroy ])
end | Only allow a list of trusted parameters through. | post_params | ruby | ledermann/docker-rails | app/controllers/posts_controller.rb | https://github.com/ledermann/docker-rails/blob/master/app/controllers/posts_controller.rb | MIT |
def open(uri_s, options = {})
leftover = extract_global_options(options)
uri = string_to_uri(uri_s)
if (name = options[:application])
app = app_for_name(name)
end
app = app_for_uri(uri) if app.nil?
app.new.open(uri, leftover)
rescue Launchy::Error => e
raise e
rescue StandardError => e
msg = "Failure in opening uri #{uri_s.inspect} with options #{options.inspect}: #{e}"
raise Launchy::Error, msg
ensure
if $ERROR_INFO && block_given?
yield $ERROR_INFO
# explicitly return here to swallow the errors if there was an error
# and we yielded to the block
# rubocop:disable Lint/EnsureReturn
return
# rubocop:enable Lint/EnsureReturn
end
end | Launch an application for the given uri string | open | ruby | copiousfreetime/launchy | lib/launchy.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy.rb | ISC |
def debug?
@debug || to_bool(ENV.fetch("LAUNCHY_DEBUG", nil))
end | we may do logging before a call to 'open', hence the need to check
LAUNCHY_DEBUG here | debug? | ruby | copiousfreetime/launchy | lib/launchy.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy.rb | ISC |
def handling(uri)
klass = find_child(:handles?, uri)
return klass if klass
raise ApplicationNotFoundError, "No application found to handle '#{uri}'"
end | Find the application that handles the given uri.
returns the Class that can handle the uri | handling | ruby | copiousfreetime/launchy | lib/launchy/application.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb | ISC |
def for_name(name)
klass = find_child(:has_name?, name)
return klass if klass
raise ApplicationNotFoundError, "No application found named '#{name}'"
end | Find the application with the given name
returns the Class that has the given name | for_name | ruby | copiousfreetime/launchy | lib/launchy/application.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb | ISC |
def find_executable(bin, *paths)
paths = Launchy.path.split(File::PATH_SEPARATOR) if paths.empty?
paths.each do |path|
file = File.join(path, bin)
if File.executable?(file)
Launchy.log "#{name} : found executable #{file}"
return file
end
end
Launchy.log "#{name} : Unable to find `#{bin}' in #{paths.join(', ')}"
nil
end | Find the given executable in the available paths
returns the path to the executable or nil if not found | find_executable | ruby | copiousfreetime/launchy | lib/launchy/application.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb | ISC |
def has_name?(qname)
qname.to_s.downcase == name.split("::").last.downcase
end | Does this class have the given name-like string?
returns true if the class has the given name | has_name? | ruby | copiousfreetime/launchy | lib/launchy/application.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/application.rb | ISC |
def children
@children = [] unless defined? @children
@children
end | The list of children that are registered | children | ruby | copiousfreetime/launchy | lib/launchy/descendant_tracker.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/descendant_tracker.rb | ISC |
def find_child(method, *args)
children.find do |child|
Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}"
child.send(method, *args)
end
end | Find one of the child classes by calling the given method
and passing all the rest of the parameters to that method in
each child | find_child | ruby | copiousfreetime/launchy | lib/launchy/descendant_tracker.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/descendant_tracker.rb | ISC |
def shell_commands(cmd, args)
cmdline = [cmd.to_s.shellsplit]
cmdline << args.flatten.collect(&:to_s)
commandline_normalize(cmdline)
end | cut it down to just the shell commands that will be passed to exec or
posix_spawn. The cmd argument is split according to shell rules and the
args are not escaped because the whole set is passed to system as *args
and in that case system shell escaping rules are not done. | shell_commands | ruby | copiousfreetime/launchy | lib/launchy/runner.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/runner.rb | ISC |
def windows_app_list
['start \\"launchy\\" /b']
end | The escaped \\ is necessary so that when shellsplit is done later,
the "launchy", with quotes, goes through to the commandline, since that | windows_app_list | ruby | copiousfreetime/launchy | lib/launchy/applications/browser.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/applications/browser.rb | ISC |
def browser_cmdline
browser_env.each do |p|
Launchy.log "#{self.class.name} : possibility from BROWSER environment variable : #{p}"
end
app_list.each do |p|
Launchy.log "#{self.class.name} : possibility from app_list : #{p}"
end
possibilities = (browser_env + app_list).flatten
if (browser = possibilities.shift)
Launchy.log "#{self.class.name} : Using browser value '#{browser}'"
return browser
end
raise Launchy::CommandNotFoundError,
"Unable to find a browser command. If this is unexpected, #{Launchy.bug_report_message}"
end | Get the full commandline of what we are going to add the uri to | browser_cmdline | ruby | copiousfreetime/launchy | lib/launchy/applications/browser.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/applications/browser.rb | ISC |
def open(uri, options = {})
cmd, args = cmd_and_args(uri, options)
run(cmd, args)
end | final assembly of the command and do %s substitution
http://www.catb.org/~esr/BROWSER/index.html | open | ruby | copiousfreetime/launchy | lib/launchy/applications/browser.rb | https://github.com/copiousfreetime/launchy/blob/master/lib/launchy/applications/browser.rb | ISC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.