Skip to content

Commit

Permalink
Reformat code with Rubocop and manually adjust styles
Browse files Browse the repository at this point in the history
  • Loading branch information
knu committed Apr 18, 2023
1 parent c5f4435 commit 930da10
Show file tree
Hide file tree
Showing 89 changed files with 1,685 additions and 1,392 deletions.
15 changes: 9 additions & 6 deletions app/concerns/email_concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ module EmailConcern
end

def validate_email_options
errors.add(:base, "subject and expected_receive_period_in_days are required") unless options['subject'].present? && options['expected_receive_period_in_days'].present?
errors.add(
:base,
"subject and expected_receive_period_in_days are required"
) unless options['subject'].present? && options['expected_receive_period_in_days'].present?

if options['recipients'].present?
emails = options['recipients']
emails = [emails] if emails.is_a?(String)
unless emails.all? { |email| email =~ Devise.email_regexp || email =~ /\{/ }
unless emails.all? { |email| Devise.email_regexp === email || /\{/ === email }
errors.add(:base, "'when provided, 'recipients' should be an email address or an array of email addresses")
end
end
Expand All @@ -40,16 +43,16 @@ def present(payload)
if payload.is_a?(Hash)
payload = ActiveSupport::HashWithIndifferentAccess.new(payload)
MAIN_KEYS.each do |key|
return { :title => payload[key].to_s, :entries => present_hash(payload, key) } if payload.has_key?(key)
return { title: payload[key].to_s, entries: present_hash(payload, key) } if payload.has_key?(key)
end

{ :title => "Event", :entries => present_hash(payload) }
{ title: "Event", entries: present_hash(payload) }
else
{ :title => payload.to_s, :entries => [] }
{ title: payload.to_s, entries: [] }
end
end

def present_hash(hash, skip_key = nil)
hash.to_a.sort_by {|a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact
hash.to_a.sort_by { |a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact
end
end
6 changes: 3 additions & 3 deletions app/concerns/event_headers_concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ def validate_event_headers_options!
def event_headers_normalizer
case interpolated['event_headers_style']
when nil, '', 'capitalized'
->name { name.gsub(/[^-]+/, &:capitalize) }
->(name) { name.gsub(/[^-]+/, &:capitalize) }
when 'downcased'
:downcase.to_proc
when 'snakecased', nil
->name { name.tr('A-Z-', 'a-z_') }
when 'snakecased'
->(name) { name.tr('A-Z-', 'a-z_') }
when 'raw'
:itself.to_proc
else
Expand Down
32 changes: 18 additions & 14 deletions app/concerns/web_request_concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ def call(env)
# Not all Faraday adapters support automatic charset
# detection, so we do that.
case env[:response_headers][:content_type]
when /;\s*charset\s*=\s*([^()<>@,;:\\\"\/\[\]?={}\s]+)/i
encoding = Encoding.find($1) rescue @default_encoding
when /;\s*charset\s*=\s*([^()<>@,;:\\"\/\[\]?={}\s]+)/i
encoding = begin
Encoding.find($1)
rescue StandardError
@default_encoding
end
when /\A\s*(?:text\/[^\s;]+|application\/(?:[^\s;]+\+)?(?:xml|json))\s*(?:;|\z)/i
encoding = @default_encoding
else
Expand All @@ -62,11 +66,11 @@ def validate_web_request_options!
if options['user_agent'].present?
errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String)
end

if options['proxy'].present?
errors.add(:base, "proxy must be a string") unless options['proxy'].is_a?(String)
end

if options['disable_ssl_verification'].present? && boolify(options['disable_ssl_verification']).nil?
errors.add(:base, "if provided, disable_ssl_verification must be true or false")
end
Expand Down Expand Up @@ -112,13 +116,13 @@ def faraday
@faraday ||= Faraday.new(faraday_options) { |builder|
builder.response :character_encoding,
force_encoding: interpolated['force_encoding'].presence,
default_encoding: default_encoding,
default_encoding:,
unzip: interpolated['unzip'].presence

builder.headers = headers if headers.length > 0

builder.headers[:user_agent] = user_agent

builder.proxy interpolated['proxy'].presence

unless boolify(interpolated['disable_redirect_follow'])
Expand All @@ -140,8 +144,8 @@ def faraday
builder.use FaradayMiddleware::Gzip

case backend = faraday_backend
when :typhoeus
require 'typhoeus/adapters/faraday'
when :typhoeus
require 'typhoeus/adapters/faraday'
end
builder.adapter backend
}
Expand All @@ -153,12 +157,12 @@ def headers(value = interpolated['headers'])

def basic_auth_credentials(value = interpolated['basic_auth'])
case value
when nil, ''
return nil
when Array
return value if value.size == 2
when /:/
return value.split(/:/, 2)
when nil, ''
return nil
when Array
return value if value.size == 2
when /:/
return value.split(/:/, 2)
end
raise ArgumentError.new("bad value for basic_auth: #{value.inspect}")
end
Expand Down
15 changes: 9 additions & 6 deletions app/controllers/agents/dry_runs_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def index
current_user.agents.find_by(id: params[:agent_id]).received_events.limit(5)
elsif params[:source_ids]
Event.where(agent_id: current_user.agents.where(id: params[:source_ids]).pluck(:id))
.order("id DESC").limit(5)
.order("id DESC").limit(5)
else
[]
end
Expand Down Expand Up @@ -40,11 +40,14 @@ def create

@results = agent.dry_run!(event)
else
@results = { events: [], memory: [],
log: [
"#{pluralize(agent.errors.count, "error")} prohibited this Agent from being saved:",
*agent.errors.full_messages
].join("\n- ") }
@results = {
events: [],
memory: [],
log: [
"#{pluralize(agent.errors.count, "error")} prohibited this Agent from being saved:",
*agent.errors.full_messages
].join("\n- ")
}
end

render layout: false
Expand Down
4 changes: 1 addition & 3 deletions app/helpers/scenario_helper.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
module ScenarioHelper

def style_colors(scenario)
colors = {
{
color: scenario.tag_fg_color || default_scenario_fg_color,
background_color: scenario.tag_bg_color || default_scenario_bg_color
}.map { |key, value| "#{key.to_s.dasherize}:#{value}" }.join(';')
Expand All @@ -19,5 +18,4 @@ def default_scenario_bg_color
def default_scenario_fg_color
'#FFFFFF'
end

end
4 changes: 2 additions & 2 deletions app/models/agent.rb
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def build_clone(original)
# Give it a unique name
2.step do |i|
name = '%s (%d)' % [original.name, i]
unless exists?(name: name)
unless exists?(name:)
clone.name = name
break
end
Expand Down Expand Up @@ -454,7 +454,7 @@ def async_receive(agent_id, event_ids)
def run_schedule(schedule)
return if schedule == 'never'

types = where(schedule: schedule).group(:type).pluck(:type)
types = where(schedule:).group(:type).pluck(:type)
types.each do |type|
next unless valid_type?(type)

Expand Down
10 changes: 5 additions & 5 deletions app/models/agent_log.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
# Agents' `last_error_log_at` column. These are often used to determine if an Agent is `working?`.
class AgentLog < ActiveRecord::Base
belongs_to :agent
belongs_to :inbound_event, :class_name => "Event", optional: true
belongs_to :outbound_event, :class_name => "Event", optional: true
belongs_to :inbound_event, class_name: "Event", optional: true
belongs_to :outbound_event, class_name: "Event", optional: true

validates_presence_of :message
validates_numericality_of :level, :only_integer => true, :greater_than_or_equal_to => 0, :less_than => 5
validates_numericality_of :level, only_integer: true, greater_than_or_equal_to: 0, less_than: 5

before_validation :scrub_message
before_save :truncate_message

def self.log_for_agent(agent, message, options = {})
puts "Agent##{agent.id}: #{message}" unless Rails.env.test?

log = agent.logs.create! options.merge(:message => message)
log = agent.logs.create! options.merge(message:)
if agent.logs.count > log_length
oldest_id_to_keep = agent.logs.limit(1).offset(log_length - 1).pluck("agent_logs.id")
agent.logs.where("agent_logs.id < ?", oldest_id_to_keep).delete_all
Expand All @@ -35,7 +35,7 @@ def self.log_length
def scrub_message
if message_changed? && !message.nil?
self.message = message.inspect unless message.is_a?(String)
self.message.scrub!{ |bytes| "<#{bytes.unpack('H*')[0]}>" }
self.message.scrub! { |bytes| "<#{bytes.unpack1('H*')}>" }
end
true
end
Expand Down
64 changes: 35 additions & 29 deletions app/models/agents/adioso_agent.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,25 @@ module Agents
class AdiosoAgent < Agent
cannot_receive_events!

default_schedule "every_1d"
default_schedule "every_1d"

description <<-MD
The Adioso Agent will tell you the minimum airline prices between a pair of cities, and within a certain period of time.
description <<~MD
The Adioso Agent will tell you the minimum airline prices between a pair of cities, and within a certain period of time.
The currency is USD. Please make sure that the difference between `start_date` and `end_date` is less than 150 days. You will need to contact [Adioso](http://adioso.com/)
for a `username` and `password`.
The currency is USD. Please make sure that the difference between `start_date` and `end_date` is less than 150 days. You will need to contact [Adioso](http://adioso.com/) for a `username` and `password`.
MD

event_description <<-MD
event_description <<~MD
If flights are present then events look like:
{
"cost": 75.23,
"date": "June 25, 2013",
"route": "New York to Chicago"
"route": "New York to Chicago"
}
otherwise
{
"nonetodest": "No flights found to the specified destination"
}
Expand All @@ -30,12 +29,12 @@ class AdiosoAgent < Agent
def default_options
{
'start_date' => Date.today.httpdate[0..15],
'end_date' => Date.today.plus_with_duration(100).httpdate[0..15],
'from' => "New York",
'to' => "Chicago",
'username' => "xx",
'password' => "xx",
'expected_update_period_in_days' => "1"
'end_date' => Date.today.plus_with_duration(100).httpdate[0..15],
'from' => "New York",
'to' => "Chicago",
'username' => "xx",
'password' => "xx",
'expected_update_period_in_days' => "1"
}
end

Expand All @@ -44,10 +43,12 @@ def working?
end

def validate_options
unless %w[start_date end_date from to username password expected_update_period_in_days].all? { |field| options[field].present? }
errors.add(:base, "All fields are required")
end
end
unless %w[
start_date end_date from to username password expected_update_period_in_days
].all? { |field| options[field].present? }
errors.add(:base, "All fields are required")
end
end

def date_to_unix_epoch(date)
date.to_time.to_i
Expand All @@ -60,19 +61,24 @@ def check
password: interpolated[:password]
}
}
parse_response = HTTParty.get "http://api.adioso.com/v2/search/parse?#{{ q: "#{interpolated[:from]} to #{interpolated[:to]}" }.to_query}", auth_options
fare_request = parse_response["search_url"].gsub /(end=)(\d*)([^\d]*)(\d*)/, "\\1#{date_to_unix_epoch(interpolated['end_date'])}\\3#{date_to_unix_epoch(interpolated['start_date'])}"
parse_response = HTTParty.get(
"http://api.adioso.com/v2/search/parse?#{{ q: "#{interpolated[:from]} to #{interpolated[:to]}" }.to_query}",
auth_options
)
fare_request = parse_response["search_url"].gsub(
/(end=)(\d*)([^\d]*)(\d*)/,
"\\1#{date_to_unix_epoch(interpolated['end_date'])}\\3#{date_to_unix_epoch(interpolated['start_date'])}"
)
fare = HTTParty.get fare_request, auth_options

if fare["warnings"]
create_event :payload => fare["warnings"]
else
event = fare["results"].min {|a,b| a["cost"] <=> b["cost"]}
event["date"] = Time.at(event["date"]).to_date.httpdate[0..15]
event["route"] = "#{interpolated['from']} to #{interpolated['to']}"
create_event :payload => event
end
if fare["warnings"]
create_event payload: fare["warnings"]
else
event = fare["results"].min_by { |x| x["cost"] }
event["date"] = Time.at(event["date"]).to_date.httpdate[0..15]
event["route"] = "#{interpolated['from']} to #{interpolated['to']}"
create_event payload: event
end
end
end
end

0 comments on commit 930da10

Please sign in to comment.