1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-11-28 09:24:24 +01:00

fixed ruby syntax in libs

This commit is contained in:
Sylvain 2019-01-31 17:15:26 +01:00
parent a528fc3766
commit 7f59b2eedb
7 changed files with 211 additions and 208 deletions

View File

@ -11,7 +11,7 @@ Metrics/AbcSize:
Metrics/ClassLength:
Max: 200
Style/BracesAroundHashParameters:
EnforcedStyle: context_dependent
EnforcedStyle: braces
Style/RegexpLiteral:
EnforcedStyle: slashes
Style/EmptyElse:

View File

@ -1,3 +1,5 @@
# frozen_string_literal: true
require_dependency 'plugin/instance'
module FabManager

View File

@ -1,17 +1,20 @@
# frozen_string_literal: true
# File size validator for CarrierWave
# https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Validate-attachment-file-size
class FileSizeValidator < ActiveModel::EachValidator
MESSAGES = { :is => :wrong_size, :minimum => :size_too_small, :maximum => :size_too_big }.freeze
CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
MESSAGES = { is: :wrong_size, minimum: :size_too_small, maximum: :size_too_big }.freeze
CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
DEFAULT_TOKENIZER = lambda { |value| value.split(//) }
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
DEFAULT_TOKENIZER = ->(value) { value.split(//) }
RESERVED_OPTIONS = %i[minimum maximum within is tokenizer too_short too_long].freeze
def initialize(options)
if range = (options.delete(:in) || options.delete(:within))
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
options[:minimum], options[:maximum] = range.begin, range.end
raise ArgumentError, ':in and :within must be a Range' unless range.is_a?(Range)
options[:minimum] = range.begin
options[:maximum] = range.end
options[:maximum] -= 1 if range.exclude_end?
end
@ -21,23 +24,19 @@ class FileSizeValidator < ActiveModel::EachValidator
def check_validity!
keys = CHECKS.keys & options.keys
if keys.empty?
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
end
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.' if keys.empty?
keys.each do |key|
value = options[key]
unless value.is_a?(Integer) && value >= 0
raise ArgumentError, ":#{key} must be a nonnegative Integer"
end
raise ArgumentError, ":#{key} must be a nonnegative Integer" unless value.is_a?(Integer) && value >= 0
end
end
def validate_each(record, attribute, value)
raise(ArgumentError, "A CarrierWave::Uploader::Base object was expected") unless value.kind_of? CarrierWave::Uploader::Base
raise(ArgumentError, 'A CarrierWave::Uploader::Base object was expected') unless value.is_a? CarrierWave::Uploader::Base
value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.kind_of?(String)
value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.is_a?(String)
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
@ -61,6 +60,7 @@ class FileSizeValidator < ActiveModel::EachValidator
Helper.instance
end
# provides dependencies
class Helper
include Singleton
include ActionView::Helpers::NumberHelper

View File

@ -1,5 +1,7 @@
# frozen_string_literal: true
active_provider = AuthProvider.active
if active_provider.providable_type != DatabaseProvider.name
require_relative "strategies/sso_#{active_provider.provider_type}_provider"
end
end

View File

@ -1,115 +1,135 @@
# frozen_string_literal: true
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class SsoOauth2Provider < OmniAuth::Strategies::OAuth2
module OmniAuth::Strategies
# Authentication strategy provided trough oAuth 2.0
class SsoOauth2Provider < OmniAuth::Strategies::OAuth2
def self.active_provider
active_provider = AuthProvider.active
if active_provider.providable_type != OAuth2Provider.name
raise "Trying to instantiate the wrong provider: Expected OAuth2Provider, received #{active_provider.providable_type}"
end
active_provider
def self.active_provider
active_provider = AuthProvider.active
if active_provider.providable_type != OAuth2Provider.name
raise "Trying to instantiate the wrong provider: Expected OAuth2Provider, received #{active_provider.providable_type}"
end
# Strategy name.
option :name, active_provider.strategy_name
active_provider
end
# Strategy name.
option :name, active_provider.strategy_name
option :client_options, {
:site => active_provider.providable.base_url,
:authorize_url => active_provider.providable.authorization_endpoint,
:token_url => active_provider.providable.token_endpoint
option :client_options,
{ site: active_provider.providable.base_url,
authorize_url: active_provider.providable.authorization_endpoint,
token_url: active_provider.providable.token_endpoint }
uid { parsed_info['user.uid'.to_sym] }
info do
{
mapping: parsed_info
}
end
uid { parsed_info['user.uid'.to_sym] }
extra do
{
raw_info: raw_info
}
end
info do
{
:mapping => parsed_info
}
end
extra do
{
:raw_info => raw_info
}
end
# retrieve data from various url, querying each only once
def raw_info
@raw_info ||= Hash.new
unless @raw_info.size > 0
OmniAuth::Strategies::SsoOauth2Provider.active_provider.providable.o_auth2_mappings.each do |mapping|
unless @raw_info.has_key?(mapping.api_endpoint.to_sym)
@raw_info[mapping.api_endpoint.to_sym] = access_token.get(mapping.api_endpoint).parsed
end
# retrieve data from various url, querying each only once
def raw_info
@raw_info ||= {}
unless @raw_info.size.positive?
OmniAuth::Strategies::SsoOauth2Provider.active_provider.providable.o_auth2_mappings.each do |mapping|
unless @raw_info.key?(mapping.api_endpoint.to_sym)
@raw_info[mapping.api_endpoint.to_sym] = access_token.get(mapping.api_endpoint).parsed
end
end
@raw_info
end
@raw_info
end
def parsed_info
@parsed_info ||= {}
unless @parsed_info.size.positive?
OmniAuth::Strategies::SsoOauth2Provider.active_provider.providable.o_auth2_mappings.each do |mapping|
def parsed_info
@parsed_info ||= Hash.new
unless @parsed_info.size > 0
OmniAuth::Strategies::SsoOauth2Provider.active_provider.providable.o_auth2_mappings.each do |mapping|
if mapping.transformation
case mapping.transformation['type']
## INTEGER
when 'integer'
@parsed_info[local_sym(mapping)] = map_integer(mapping.transformation,
mapping.api_endpoint.to_sym,
mapping.api_field)
if mapping.transformation
case mapping.transformation['type']
## INTEGER
when 'integer'
mapping.transformation['mapping'].each do |m|
if m['from'] == raw_info[mapping.api_endpoint.to_sym][mapping.api_field]
@parsed_info[local_sym(mapping)] = m['to']
break
end
end
# if no transformation had set any value, set the raw value
unless @parsed_info[local_sym(mapping)]
@parsed_info[local_sym(mapping)] = raw_info[mapping.api_endpoint.to_sym][mapping.api_field]
end
## BOOLEAN
when 'boolean'
@parsed_info[local_sym(mapping)] = map_boolean(mapping.transformation,
mapping.api_endpoint.to_sym,
mapping.api_field)
## BOOLEAN
when 'boolean'
@parsed_info[local_sym(mapping)] = !(raw_info[mapping.api_endpoint.to_sym][mapping.api_field] == mapping.transformation['false_value'])
@parsed_info[local_sym(mapping)] = (raw_info[mapping.api_endpoint.to_sym][mapping.api_field] == mapping.transformation['true_value'])
## DATE
when 'date'
@params[local_sym(mapping)] = map_date(mapping.transformation,
mapping.api_endpoint.to_sym,
mapping.api_field)
## DATE
when 'date'
case mapping.transformation['format']
when 'iso8601'
@parsed_info[local_sym(mapping)] = DateTime.iso8601(raw_info[mapping.api_endpoint.to_sym][mapping.api_field])
when 'rfc2822'
@parsed_info[local_sym(mapping)] = DateTime.rfc2822(raw_info[mapping.api_endpoint.to_sym][mapping.api_field])
when 'rfc3339'
@parsed_info[local_sym(mapping)] = DateTime.rfc3339(raw_info[mapping.api_endpoint.to_sym][mapping.api_field])
when 'timestamp-s'
@parsed_info[local_sym(mapping)] = DateTime.strptime(raw_info[mapping.api_endpoint.to_sym][mapping.api_field],'%s')
when 'timestamp-ms'
@parsed_info[local_sym(mapping)] = DateTime.strptime(raw_info[mapping.api_endpoint.to_sym][mapping.api_field],'%Q')
else
@parsed_info[local_sym(mapping)] = DateTime.parse(raw_info[mapping.api_endpoint.to_sym][mapping.api_field])
end
## OTHER TRANSFORMATIONS (not supported)
else
@parsed_info[local_sym(mapping)] = raw_info[mapping.api_endpoint.to_sym][mapping.api_field]
end
## NO TRANSFORMATION
## OTHER TRANSFORMATIONS (not supported)
else
@parsed_info[local_sym(mapping)] = raw_info[mapping.api_endpoint.to_sym][mapping.api_field]
end
## NO TRANSFORMATION
else
@parsed_info[local_sym(mapping)] = raw_info[mapping.api_endpoint.to_sym][mapping.api_field]
end
end
@parsed_info
end
@parsed_info
end
private
def local_sym(mapping)
(mapping.local_model+'.'+mapping.local_field).to_sym
private
def local_sym(mapping)
(mapping.local_model + '.' + mapping.local_field).to_sym
end
def map_integer(transformation, api_endpoint, api_field)
value = nil
transformation['mapping'].each do |m|
if m['from'] == raw_info[api_endpoint][api_field]
value = m['to']
break
end
end
# if no transformation had set any value, return the raw value
value || raw_info[api_endpoint.to_sym][api_field]
end
def map_boolean(transformation, api_endpoint, api_field)
return false if raw_info[api_endpoint][api_field] == transformation['false_value']
true if raw_info[api_endpoint][api_field] == transformation['true_value']
end
def map_date(transformation, api_endpoint, api_field)
case transformation['format']
when 'iso8601'
DateTime.iso8601(raw_info[api_endpoint][api_field])
when 'rfc2822'
DateTime.rfc2822(raw_info[api_endpoint][api_field])
when 'rfc3339'
DateTime.rfc3339(raw_info[api_endpoint][api_field])
when 'timestamp-s'
DateTime.strptime(raw_info[api_endpoint][api_field], '%s')
when 'timestamp-ms'
DateTime.strptime(raw_info[api_endpoint][api_field], '%Q')
else
DateTime.parse(raw_info[api_endpoint][api_field])
end
end
end
end
end

View File

@ -1,98 +1,97 @@
# frozen_string_literal: true
require 'fileutils'
require 'plugin_registry'
module Plugin
class Instance
attr_accessor :path#, :directory
class Plugin::Instance
attr_accessor :path
[:assets, :initializers, :javascripts, :styles].each do |att|
class_eval %Q{
def #{att}
@#{att} ||= []
end
}
end
def self.find_all(parent_path)
[].tap { |plugins|
# also follows symlinks - http://stackoverflow.com/q/357754
Dir["#{parent_path}/**/*/**/plugin.rb"].sort.each do |path|
source = File.read(path)
# metadata = Plugin::Metadata.parse(source)
plugins << self.new(nil, path)
end
}
end
def initialize(metadata=nil, path=nil)
@metadata = metadata
@path = path
#@directory = path.match(/(.*)\/plugin.rb/)[1]
@idx = 0
end
def activate!
if @path
root_path = "#{File.dirname(@path)}/assets/javascripts"
PluginRegistry.register_glob(root_path, 'coffee.erb')
%i[assets initializers javascripts styles].each do |att|
class_eval %(
def #{att}
@#{att} ||= []
end
), __FILE__, __LINE__ - 4
end
self.instance_eval File.read(path), path # execute all code of the plugin main file ! (named plugin.rb)
def self.find_all(parent_path)
[].tap { |plugins|
# also follows symlinks - http://stackoverflow.com/q/357754
Dir["#{parent_path}/**/*/**/plugin.rb"].sort.each do |path|
plugins << new(nil, path)
end
}
end
register_assets! unless assets.blank?
def initialize(metadata=nil, path=nil)
@metadata = metadata
@path = path
@idx = 0
end
Rails.configuration.assets.paths << File.dirname(path) + "/assets"
Rails.configuration.assets.precompile += [lambda do |filename, path|
(Dir["plugins/*/assets/templates"].any? { |p| path.include?(p) }) # useless because already included in application.css/js || (%w(.js).include?(File.extname(filename)) && Dir["plugins/*/assets/javascripts"].any? { |p| path.include?(p) }) || (%w(.css).include?(File.extname(filename)) && Dir["plugins/*/assets/stylesheets"].any? { |p| path.include?(p) })
end] #
Rails.configuration.sass.load_paths += Dir["plugins/*/assets/stylesheets"]
# Automatically include rake tasks
Rake.add_rakelib(File.dirname(path) + "/lib/tasks")
# Automatically include migrations
Rails.configuration.paths["db/migrate"] << File.dirname(path) + "/db/migrate"
def activate!
if @path
root_path = "#{File.dirname(@path)}/assets/javascripts"
PluginRegistry.register_glob(root_path, 'coffee.erb')
end
def register_asset(file, opts=nil) # to be used by the plugin !
full_path = File.dirname(path) << "/assets/" << file
assets << [full_path, opts]
end
instance_eval File.read(path), path # execute all code of the plugin main file ! (named plugin.rb)
def register_code_insertion(key, code)
PluginRegistry.code_insertions[key] ||= []
PluginRegistry.code_insertions[key] << code
end
register_assets! unless assets.blank?
def register_css(style) # useless ?
styles << style
end
Rails.configuration.assets.paths << "#{File.dirname(path)}/assets"
def after_initialize(&block)
initializers << block
end
Rails.configuration.assets.precompile += [lambda do |_filename, path|
(Dir['plugins/*/assets/templates'].any? { |p| path.include?(p) })
end]
def notify_after_initialize
initializers.each do |callback|
begin
callback.call(self)
rescue ActiveRecord::StatementInvalid => e
# When running db:migrate for the first time on a new database, plugin initializers might
# try to use models. Tolerate it.
raise e unless e.message.try(:include?, "PG::UndefinedTable")
end
Rails.configuration.sass.load_paths += Dir['plugins/*/assets/stylesheets']
# Automatically include rake tasks
Rake.add_rakelib("#{File.dirname(path)}/lib/tasks")
# Automatically include migrations
Rails.configuration.paths['db/migrate'] << "#{File.dirname(path)}/db/migrate"
end
# to be used by the plugin !
def register_asset(file, opts=nil)
full_path = File.dirname(path) << '/assets/' << file
assets << [full_path, opts]
end
def register_code_insertion(key, code)
PluginRegistry.code_insertions[key] ||= []
PluginRegistry.code_insertions[key] << code
end
# useless ?
def register_css(style)
styles << style
end
def after_initialize(&block)
initializers << block
end
def notify_after_initialize
initializers.each do |callback|
begin
callback.call(self)
rescue ActiveRecord::StatementInvalid => e
# When running db:migrate for the first time on a new database, plugin initializers might
# try to use models. Tolerate it.
raise e unless e.message.try(:include?, 'PG::UndefinedTable')
end
end
end
protected
def register_assets!
assets.each do |asset, opts|
PluginRegistry.register_asset(asset, opts)
end
end
protected
def register_assets!
assets.each do |asset, opts|
PluginRegistry.register_asset(asset, opts)
end
end
end

View File

@ -21,38 +21,18 @@ class PluginRegistry
end
def self.register_glob(root, extension, options=nil)
self.asset_globs << [root, extension, options || {}]
asset_globs << [root, extension, options || {}]
end
def self.register_asset(asset, opts=nil)
def self.register_asset(asset, _opts = nil)
if asset =~ /\.js$|\.js\.erb$|\.js\.es6$|\.coffee$|\.coffee\.erb/
# if opts == :admin
# self.admin_javascripts << asset
# else
# if opts == :server_side
# self.server_side_javascripts << asset
# end
self.javascripts << asset
# end
javascripts << asset
elsif asset =~ /\.css$|\.scss$/
# if opts == :mobile
# self.mobile_stylesheets << asset
# elsif opts == :desktop
# self.desktop_stylesheets << asset
# elsif opts == :variables
# self.sass_variables << asset
# else
self.stylesheets << asset
# end
# elsif asset =~ /\.hbs$/
# self.handlebars << asset
# elsif asset =~ /\.js\.handlebars$/
# self.handlebars << asset
stylesheets << asset
end
end
def self.insert_code(key)
self.code_insertions[key]&.join('\n')
code_insertions[key]&.join('\n')
end
end