Use boolean comparators where it makes sense

This commit is contained in:
wvengen 2015-01-14 21:15:08 +01:00
parent dbdc7ae4aa
commit 118886344a
28 changed files with 60 additions and 60 deletions

View File

@ -17,10 +17,10 @@ module Admin::ConfigsHelper
config_input_field_options form, key, options[:input_html]
config_input_tooltip_options form, key, options[:input_html]
if options[:as] == :boolean
options[:input_html][:checked] = 'checked' if v=options[:input_html].delete(:value) and v!='false'
options[:input_html][:checked] = 'checked' if v=options[:input_html].delete(:value) && v!='false'
options[:checked_value] = 'true' if options[:checked_value].nil?
options[:unchecked_value] = 'false' if options[:unchecked_value].nil?
elsif options[:collection] or options[:as] == :select
elsif options[:collection] || options[:as] == :select
options[:selected] = options[:input_html].delete(:value)
return form.input key, options, &block
elsif options[:as] == :time_zone
@ -53,7 +53,7 @@ module Admin::ConfigsHelper
if options[:as] == :boolean
checked_value = options.delete(:checked_value) || 'true'
unchecked_value = options.delete(:unchecked_value) || 'false'
options[:checked] = 'checked' if v=options.delete(:value) and v!='false'
options[:checked] = 'checked' if v=options.delete(:value) && v!='false'
form.hidden_field(key, value: unchecked_value, as: :hidden) + form.check_box(key, options, checked_value, false)
elsif options[:as] == :select_recurring
options[:value] = FoodsoftDateUtil.rule_from(options[:value])

View File

@ -16,7 +16,7 @@ module ApplicationHelper
end
def format_datetime_timespec(time, format)
I18n.l(time, :format => format) unless (time.nil? or format.nil?)
I18n.l(time, :format => format) unless (time.nil? || format.nil?)
end
# Creates ajax-controlled-links for pagination
@ -92,7 +92,7 @@ module ApplicationHelper
if options[:short]
desc = options[:desc]
desc ||= model.human_attribute_name("#{attribute}_desc".to_sym, options.merge({fallback: true, default: '', count: 2}))
desc.blank? and desc = s
desc.blank? && desc = s
sshort = model.human_attribute_name("#{attribute}_short".to_sym, options.merge({fallback: true, default: '', count: 2}))
s = raw "<abbr title='#{desc}'>#{sshort}</abbr>" unless sshort.blank?
end
@ -187,7 +187,7 @@ module ApplicationHelper
# render base errors in a form after failed validation
# http://railsapps.github.io/twitter-bootstrap-rails.html
def base_errors resource
return '' if (resource.errors.empty?) or (resource.errors[:base].empty?)
return '' if resource.errors.empty? || resource.errors[:base].empty?
messages = resource.errors[:base].map { |msg| content_tag(:li, msg) }.join
render :partial => 'shared/base_errors', :locals => {:error_messages => messages}
end
@ -197,7 +197,7 @@ module ApplicationHelper
if user.nil?
"?"
elsif FoodsoftConfig[:use_nick]
if options[:full] and options[:markup]
if options[:full] && options[:markup]
raw "<b>#{h user.nick}</b> (#{h user.first_name} #{h user.last_name})"
elsif options[:full]
"#{user.nick} (#{user.first_name} #{user.last_name})"
@ -217,7 +217,7 @@ module ApplicationHelper
# allow truncate to add title when tooltip option is given
def truncate(text, options={}, &block)
return text if not text or text.length <= (options[:length] or 30)
return text if !text || text.length <= (options[:length] || 30)
text_truncated = super(text, options, &block)
if options[:tooltip]
content_tag :span, text_truncated, title: text

View File

@ -2,7 +2,7 @@ module GroupOrderArticlesHelper
# return an edit field for a GroupOrderArticle result
def group_order_article_edit_result(goa)
unless goa.group_order.order.finished? and current_user.role_finance?
unless goa.group_order.order.finished? && current_user.role_finance?
goa.result
else
simple_form_for goa, remote: true, html: {'data-submit-onchange' => 'changed', class: 'delta-input'} do |f|

View File

@ -11,7 +11,7 @@ module GroupOrdersHelper
# If the option :show is true, the link is for showing the group_order.
def link_to_ordering(order, options = {}, &block)
group_order = order.group_order(current_user.ordergroup)
path = if options[:show] and group_order
path = if options[:show] && group_order
group_order_path(group_order)
elsif group_order
edit_group_order_path(group_order, :order_id => order.id)

View File

@ -48,12 +48,12 @@ module OrdersHelper
# Sensible in tables with multiple columns.
# @return [String] Text showing unit and unit quantity when applicable.
def pkg_helper(article, options={})
return '' if not article or article.unit_quantity == 1
return '' if !article || article.unit_quantity == 1
uq_text = "× #{article.unit_quantity}"
uq_text = content_tag(:span, uq_text, class: 'hidden-phone') if options[:soft_uq]
if options[:plain]
uq_text
elsif options[:icon].nil? or options[:icon]
elsif options[:icon].nil? || options[:icon]
pkg_helper_icon(uq_text)
else
pkg_helper_icon(uq_text, tag: :span)
@ -80,7 +80,7 @@ module OrdersHelper
def receive_input_field(form)
order_article = form.object
units_expected = (order_article.units_billed or order_article.units_to_order) *
units_expected = (order_article.units_billed || order_article.units_to_order) *
1.0 * order_article.article.unit_quantity / order_article.article_price.unit_quantity
input_classes = 'input input-nano units_received'
@ -117,7 +117,7 @@ module OrdersHelper
# @param order_or_supplier [Order, Supplier] Order or supplier to link to
# @return [String] Link to order or supplier, showing its name.
def supplier_link(order_or_supplier)
if order_or_supplier.kind_of?(Order) and order_or_supplier.stockit?
if order_or_supplier.kind_of?(Order) && order_or_supplier.stockit?
link_to(order_or_supplier.name, stock_articles_path).html_safe
else
link_to(@order.supplier.name, supplier_path(@order.supplier)).html_safe

View File

@ -103,13 +103,13 @@ class Article < ActiveRecord::Base
def shared_article_changed?(supplier = self.supplier)
# skip early if the timestamp hasn't changed
shared_article = self.shared_article(supplier)
unless shared_article.nil? or self.shared_updated_on == shared_article.updated_on
unless shared_article.nil? || self.shared_updated_on == shared_article.updated_on
# try to convert units
# convert supplier's price and unit_quantity into fc-size
new_price, new_unit_quantity = self.convert_units
new_unit = self.unit
unless new_price and new_unit_quantity
unless new_price && new_unit_quantity
# if convertion isn't possible, take shared_article-price/unit_quantity
new_price, new_unit_quantity, new_unit = shared_article.price, shared_article.unit_quantity, shared_article.unit
end
@ -142,7 +142,7 @@ class Article < ActiveRecord::Base
# compare attributes from different articles. used for auto-synchronization
# returns array of symbolized unequal attributes
def self.compare_attributes(attributes)
unequal_attributes = attributes.select { |name, values| values[0] != values[1] and not (values[0].blank? and values[1].blank?) }
unequal_attributes = attributes.select { |name, values| values[0] != values[1] && !(values[0].blank? && values[1].blank?) }
unequal_attributes.collect { |pair| pair[0] }
end
@ -160,10 +160,10 @@ class Article < ActiveRecord::Base
def convert_units
if unit != shared_article.unit
# legacy, used by foodcoops in Germany
if shared_article.unit == "KI" and unit == "ST" # 'KI' means a box, with a different amount of items in it
if shared_article.unit == "KI" && unit == "ST" # 'KI' means a box, with a different amount of items in it
# try to match the size out of its name, e.g. "banana 10-12 St" => 10
new_unit_quantity = /[0-9\-\s]+(St)/.match(shared_article.name).to_s.to_i
if new_unit_quantity and new_unit_quantity > 0
if new_unit_quantity && new_unit_quantity > 0
new_price = (shared_article.price/new_unit_quantity.to_f).round(2)
[new_price, new_unit_quantity]
else
@ -172,7 +172,7 @@ class Article < ActiveRecord::Base
else # use ruby-units to convert
fc_unit = (::Unit.new(unit) rescue nil)
supplier_unit = (::Unit.new(shared_article.unit) rescue nil)
if fc_unit and supplier_unit and fc_unit =~ supplier_unit
if fc_unit && supplier_unit && fc_unit =~ supplier_unit
conversion_factor = (supplier_unit / fc_unit).to_base.to_r
new_price = shared_article.price / conversion_factor
new_unit_quantity = shared_article.unit_quantity * conversion_factor
@ -225,7 +225,7 @@ class Article < ActiveRecord::Base
matches = Article.where(name: name, supplier_id: supplier_id, deleted_at: deleted_at, type: type)
matches = matches.where.not(id: id) unless new_record?
# supplier should always be there - except, perhaps, on initialization (on seeding)
if supplier and (supplier.shared_sync_method.blank? or supplier.shared_sync_method == 'import')
if supplier && (supplier.shared_sync_method.blank? || supplier.shared_sync_method == 'import')
errors.add :name, :taken if matches.any?
else
errors.add :name, :taken_with_unit if matches.where(unit: unit, unit_quantity: unit_quantity).any?

View File

@ -19,14 +19,14 @@ class ArticleCategory < ActiveRecord::Base
# Find a category that matches a category name; may return nil.
# TODO more intelligence like remembering earlier associations (global and/or per-supplier)
def self.find_match(category)
return if category.blank? or category.length < 3
return if category.blank? || category.length < 3
c = nil
## exact match - not needed, will be returned by next query as well
#c ||= ArticleCategory.where(name: category).first
# case-insensitive substring match (take the closest match = shortest)
c = ArticleCategory.where('name LIKE ?', "%#{category}%") unless c and c.any?
c = ArticleCategory.where('name LIKE ?', "%#{category}%") unless c && c.any?
# case-insensitive phrase present in category description
c = ArticleCategory.where('description LIKE ?', "%#{category}%").select {|s| s.description.match /(^|,)\s*#{category}\s*(,|$)/i} unless c and c.any?
c = ArticleCategory.where('description LIKE ?', "%#{category}%").select {|s| s.description.match /(^|,)\s*#{category}\s*(,|$)/i} unless c && c.any?
# return closest match if there are multiple
c = c.sort_by {|s| s.name.length}.first if c.respond_to? :sort_by
c

View File

@ -36,7 +36,7 @@ class GroupOrderArticle < ActiveRecord::Base
logger.debug("Current quantity = #{self.quantity}, tolerance = #{self.tolerance}")
# When quantity and tolerance are zero, we don't serve any purpose
if quantity == 0 and tolerance == 0
if quantity == 0 && tolerance == 0
logger.debug("Self-destructing since requested quantity and tolerance are zero")
destroy!
return
@ -108,7 +108,7 @@ class GroupOrderArticle < ActiveRecord::Base
# See description of the ordering algorithm in the general application documentation for details.
def calculate_result(total = nil)
# return memoized result unless a total is given
return @calculate_result if total.nil? and not @calculate_result.nil?
return @calculate_result if total.nil? && !@calculate_result.nil?
quantity = tolerance = total_quantity = 0

View File

@ -50,7 +50,7 @@ class Order < ActiveRecord::Base
# but which have already been ordered in this stock order
StockArticle.available.includes(:article_category).
order('article_categories.name', 'articles.name').reject{ |a|
a.quantity_available <= 0 and not a.ordered_in_order?(self)
a.quantity_available <= 0 && !a.ordered_in_order?(self)
}.group_by { |a| a.article_category.name }
else
supplier.articles.available.group_by { |a| a.article_category.name }
@ -260,8 +260,8 @@ class Order < ActiveRecord::Base
def keep_ordered_articles
chosen_order_articles = order_articles.where(article_id: article_ids)
to_be_removed = order_articles - chosen_order_articles
to_be_removed_but_ordered = to_be_removed.select { |a| a.quantity > 0 or a.tolerance > 0 }
unless to_be_removed_but_ordered.empty? or ignore_warnings
to_be_removed_but_ordered = to_be_removed.select { |a| a.quantity > 0 || a.tolerance > 0 }
unless to_be_removed_but_ordered.empty? || ignore_warnings
errors.add(:articles, I18n.t(stockit? ? 'orders.model.warning_ordered_stock' : 'orders.model.warning_ordered'))
@erroneous_article_ids = to_be_removed_but_ordered.map { |a| a.article_id }
end

View File

@ -122,13 +122,13 @@ class OrderArticle < ActiveRecord::Base
qty_left -= qty_for_members
# if there's anything left, move to stock if wanted
if qty_left > 0 and surplus.index(:stock)
if qty_left > 0 && surplus.index(:stock)
counts[surplus.index(:stock)] = qty_left
# 1) find existing stock article with same name, unit, price
# 2) if not found, create new stock article
# avoiding duplicate stock article names
end
if qty_left > 0 and surplus.index(nil)
if qty_left > 0 && surplus.index(nil)
counts[surplus.index(nil)] = qty_left
end
@ -181,7 +181,7 @@ class OrderArticle < ActiveRecord::Base
end
def update_global_price=(value)
@update_global_price = (value == true or value == '1') ? true : false
@update_global_price = (value == true || value == '1') ? true : false
end
# @return [Number] Units missing for the last +unit_quantity+ of the article.
@ -207,7 +207,7 @@ class OrderArticle < ActiveRecord::Base
# Associate with current article price if created in a finished order
def init_from_balancing
if order.present? and order.finished?
if order.present? && order.finished?
self.article_price = article.article_prices.first
end
end

View File

@ -85,11 +85,11 @@ class Ordergroup < Group
# The restriction can be deactivated for each ordergroup.
# Only ordergroups, which have participated in more than 5 orders in total and more than 2 orders in apple time period
def not_enough_apples?
FoodsoftConfig[:use_apple_points] and
FoodsoftConfig[:stop_ordering_under].present? and
!ignore_apple_restriction and
apples < FoodsoftConfig[:stop_ordering_under] and
group_orders.count > 5 and
FoodsoftConfig[:use_apple_points] &&
FoodsoftConfig[:stop_ordering_under].present? &&
!ignore_apple_restriction &&
apples < FoodsoftConfig[:stop_ordering_under] &&
group_orders.count > 5 &&
group_orders.joins(:order).merge(Order.finished).where('orders.ends >= ?', APPLE_MONTH_AGO.month.ago).count > 2
end

View File

@ -39,7 +39,7 @@ class Supplier < ActiveRecord::Base
# try to convert different units
new_price, new_unit_quantity = article.convert_units
if new_price and new_unit_quantity
if new_price && new_unit_quantity
article.price = new_price
article.unit_quantity = new_unit_quantity
else
@ -98,7 +98,7 @@ class Supplier < ActiveRecord::Base
# make sure the shared_sync_method is allowed for the shared supplier
def valid_shared_sync_method
if shared_supplier and !shared_supplier.shared_sync_methods.include?(shared_sync_method)
if shared_supplier && !shared_supplier.shared_sync_methods.include?(shared_sync_method)
errors.add :name, :included
end
end

View File

@ -160,7 +160,7 @@ class User < ActiveRecord::Base
end
def self.authenticate(login, password)
user = (find_by_nick(login) or find_by_email(login))
user = find_by_nick(login) || find_by_email(login)
if user && user.has_password(password)
user
else

View File

@ -23,7 +23,7 @@ namespace :deploy do
task :config => ['deploy:set_rails_env'] do
require 'securerandom'
on roles(:app), in: :groups do
db_name = (fetch(:db_user) or fetch(:application))
db_name = fetch(:db_user) || fetch(:application)
db_passwd = SecureRandom.urlsafe_base64(24).to_s
db_yaml = {
fetch(:rails_env).to_s => {

View File

@ -28,7 +28,7 @@ namespace :enable_plugins do
text = capture :cat, shared_path.join('config/plugins.yml'), '||true'
if text
plugins = YAML.load(text)
enable_foodsoft_plugins(plugins['enabled']) if plugins and not plugins['enabled'].nil?
enable_foodsoft_plugins(plugins['enabled']) if plugins && !plugins['enabled'].nil?
end
end
end

View File

@ -11,7 +11,7 @@ namespace :resque do
on roles(:resque), in: :groups do
SSHKit.config.command_map[:rake_as_run_user] =
unless fetch(:run_user).nil? or fetch(:run_user) == fetch(:user)
unless fetch(:run_user).nil? || fetch(:run_user) == fetch(:user)
"sudo -u '#{fetch(:run_user)}' "
else
''

View File

@ -19,7 +19,7 @@ module DateTimeAttributeValidate
if self.instance_variable_get("@#{attribute}_is_set")
date = self.instance_variable_get("@#{attribute}_date_value")
time = self.instance_variable_get("@#{attribute}_time_value")
if date.blank? and time.blank?
if date.blank? && time.blank?
self.send("#{attribute}=", nil)
end
end
@ -50,11 +50,11 @@ module DateTimeAttributeValidate
# validate date and time
define_method("#{attribute}_datetime_value_valid") do
date = self.instance_variable_get("@#{attribute}_date_value")
unless date.blank? or (Date.parse(date) rescue nil)
unless date.blank? || (Date.parse(date) rescue nil)
errors.add(attribute, "is not a valid date") # @todo I18n
end
time = self.instance_variable_get("@#{attribute}_time_value")
unless time.blank? or (Time.parse(time) rescue nil)
unless time.blank? || (Time.parse(time) rescue nil)
errors.add(attribute, "is not a valid time") # @todo I18n
end
end

View File

@ -94,7 +94,7 @@ class FoodsoftConfig
# @param key [String, Symbol]
# @return [Object] Value of the key.
def [](key)
if RailsSettings::CachedSettings.table_exists? and allowed_key?(key)
if RailsSettings::CachedSettings.table_exists? && allowed_key?(key)
value = RailsSettings::CachedSettings["foodcoop.#{self.scope}.#{key}"]
value = config[key] if value.nil?
value
@ -113,7 +113,7 @@ class FoodsoftConfig
return false unless allowed_key?(key)
value = normalize_value value
# then update database
if config[key] == value or (config[key].nil? and value == false)
if config[key] == value || (config[key].nil? && value == false)
# delete (ok if it was already deleted)
begin
RailsSettings::CachedSettings.destroy "foodcoop.#{self.scope}.#{key}"

View File

@ -7,7 +7,7 @@ module FoodsoftDateUtil
# @todo handle ical parse errors
occ = (schedule.next_occurrence(from).to_time rescue nil)
end
if occ and options[:time]
if occ && options[:time]
occ = occ.beginning_of_day.advance(seconds: Time.parse(options[:time]).seconds_since_midnight)
end
occ

View File

@ -42,7 +42,7 @@ namespace :foodsoft do
if tg.has_next_task?
create_until = Date.today + FoodsoftConfig[:tasks_upfront_days].to_i + 1
rake_say "creating until #{create_until}"
while tg.next_task_date.nil? or tg.next_task_date < create_until
while tg.next_task_date.nil? || tg.next_task_date < create_until
tg.create_next_task
end
end

View File

@ -126,7 +126,7 @@ end
def ask(question, answers = false)
puts question
input = STDIN.gets.chomp
if input.blank? or (answers and !answers.include?(input))
if input.blank? || (answers && !answers.include?(input))
puts red "Your Input is not valid. Try again!"
input = ask(question, answers)
end

View File

@ -15,7 +15,7 @@ class TokenVerifier < ActiveSupport::MessageVerifier
def verify(message)
r = super(message)
raise InvalidMessage unless r.is_a?(Array) and r.length >= 2 and r.length <= 3
raise InvalidMessage unless r.is_a?(Array) && r.length >= 2 && r.length <= 3
raise InvalidScope unless r[0] == FoodsoftConfig.scope
raise InvalidPrefix unless r[1] == @_prefix
# return original message
@ -34,7 +34,7 @@ class TokenVerifier < ActiveSupport::MessageVerifier
def self.secret
# secret_key_base for Rails 4, but Rails 3 initializer may still be used
Foodsoft::Application.config.secret_key_base or Foodsoft::Application.config.secret_token
Foodsoft::Application.config.secret_key_base || Foodsoft::Application.config.secret_token
end
end

View File

@ -10,7 +10,7 @@ class MessagesController < ApplicationController
# Creates a new message object.
def new
@message = Message.new(params[:message])
if @message.reply_to and not @message.reply_to.is_readable_for?(current_user)
if @message.reply_to && !@message.reply_to.is_readable_for?(current_user)
redirect_to new_message_url, alert: 'Nachricht ist privat!'
end
end

View File

@ -6,7 +6,7 @@ module FoodsoftMessages
# modify user presentation link to writing a message for the user
def show_user_link(user=@current_user)
if user.nil? or not FoodsoftMessages.enabled?
if user.nil? || !FoodsoftMessages.enabled?
show_user user
else
link_to show_user(user), new_message_path('message[mail_to]' => user.id),

View File

@ -4,7 +4,7 @@ require "foodsoft_uservoice/engine"
module FoodsoftUservoice
# enabled when configured, but can still be disabled by use_uservoice option
def self.enabled?
FoodsoftConfig[:use_uservoice] != false and FoodsoftConfig[:uservoice]
FoodsoftConfig[:use_uservoice] != false && FoodsoftConfig[:uservoice]
end
module LoadUservoice

View File

@ -84,7 +84,7 @@ class PagesController < ApplicationController
else
if @page.save
@page.parent_id = parent_id if (!params[:parent_id].blank? \
and params[:parent_id] != @page_id)
&& params[:parent_id] != @page_id)
flash[:notice] = I18n.t('pages.update.notice')
redirect_to wiki_page_path(@page.permalink)
else

View File

@ -62,7 +62,7 @@ module PagesHelper
def parent_pages_to_select(current_page)
unless current_page.homepage? # Homepage is the page trees root!
Page.non_redirected.reject { |p| p == current_page or p.ancestors.include?(current_page) }
Page.non_redirected.reject { |p| p == current_page || p.ancestors.include?(current_page) }
else
Array.new
end

View File

@ -1,7 +1,7 @@
- content = wikified_body @page.body, @page.title
- toc = generate_toc @page.body
- unless toc.blank? or params[:preview]
- unless toc.blank? || params[:preview]
- content_for :sidebar do
#wikitoc.well.well-small
%h3= t '.title_toc'