ru.Bee 1.3.2 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
1
  module Rubee
2
- class SidekiqAsync
3
- def perform_async(**args)
4
- options = if args[:options].is_a? Hash
5
- [JSON.generate(args[:options])]
6
- elsif args[:options].is_a? Array
7
- args[:options]
8
- else
9
- [args[:options]]
10
- end
2
+ class SidekiqAsync
3
+ def perform_async(**args)
4
+ options = if args[:options].is_a?(Hash)
5
+ [JSON.generate(args[:options])]
6
+ elsif args[:options].is_a?(Array)
7
+ args[:options]
8
+ else
9
+ [args[:options]]
10
+ end
11
11
 
12
- args[:_class].perform_async(*options)
12
+ args[:_class].perform_async(*options)
13
+ end
13
14
  end
14
15
  end
15
- end
@@ -1,7 +1,7 @@
1
1
  module Rubee
2
2
  class ThreadAsync
3
3
  def perform_async(**args)
4
- color_puts "WARN: ThreadAsync engine is not yet recommended for production", color: :yellow
4
+ color_puts('WARN: ThreadAsync engine is not yet recommended for production', color: :yellow)
5
5
  ThreadPool.instance.enqueue(args[:_class], args[:options])
6
6
  end
7
7
  end
@@ -23,7 +23,7 @@ module Rubee
23
23
 
24
24
  def shutdown
25
25
  @running = false
26
- THREADS_LIMIT.times { @queue << { task: :stop, args: nil } }
26
+ THREADS_LIMIT.times { @queue << { task: :stop, args: nil } }
27
27
  @workers.each(&:join)
28
28
  end
29
29
 
@@ -39,6 +39,7 @@ module Rubee
39
39
  args = task_hash[:args]
40
40
  end
41
41
  break if task == :stop
42
+
42
43
  begin
43
44
  task.new.perform(**args)
44
45
  rescue StandardError => e
@@ -50,4 +51,3 @@ module Rubee
50
51
  end
51
52
  end
52
53
  end
53
-
@@ -12,37 +12,38 @@ module Rubee
12
12
 
13
13
  if File.exist?(image_path) && File.file?(image_path)
14
14
  mime_type = Rack::Mime.mime_type(File.extname(image_path))
15
- response_with object: File.read(image_path), type: :image, mime_type: mime_type
15
+ response_with(object: File.read(image_path), type: :image, mime_type: mime_type)
16
16
  else
17
- response_with object: "Image not found", type: :text
17
+ response_with(object: 'Image not found', type: :text)
18
18
  end
19
19
  end
20
20
 
21
- def response_with type: nil, object: nil, status: 200, mime_type: nil, render_view: nil, headers: {}, to: nil, file: nil, filename: nil, **options
21
+ def response_with type: nil, object: nil, status: 200, mime_type: nil, render_view: nil, headers: {}, to: nil,
22
+ file: nil, filename: nil, **options
22
23
  case type&.to_sym
23
24
  in :json
24
25
  rendered_json = object.is_a?(Array) ? object&.map(&:to_h).to_json : object.to_json
25
- return [status, headers.merge("content-type" => "application/json"), [rendered_json]]
26
+ [status, headers.merge('content-type' => 'application/json'), [rendered_json]]
26
27
  in :image
27
- return [status, headers.merge("content-type" => mime_type), [object]]
28
+ [status, headers.merge('content-type' => mime_type), [object]]
28
29
  in :file
29
- return [
30
+ [
30
31
  status,
31
32
  headers.merge(
32
- "content-disposition" => "attachment; filename=#{filename}",
33
- "content-type" => "application/octet-stream"
33
+ 'content-disposition' => "attachment; filename=#{filename}",
34
+ 'content-type' => 'application/octet-stream'
34
35
  ),
35
- file
36
+ file,
36
37
  ]
37
38
  in :text
38
- return [status, headers.merge("content-type" => "text/plain"), [object.to_s]]
39
+ [status, headers.merge('content-type' => 'text/plain'), [object.to_s]]
39
40
  in :unauthentificated
40
- return [401, headers.merge("content-type" => "text/plain"), ["Unauthentificated"]]
41
+ [401, headers.merge('content-type' => 'text/plain'), ['Unauthentificated']]
41
42
  in :redirect
42
- return [302, headers.merge("location" => "#{to}"), ["Unauthentificated"]]
43
+ [302, headers.merge('location' => to.to_s), ['Unauthentificated']]
43
44
  else # rendering erb view is a default behavior
44
- view_file_name = self.class.name.split("Controller").first.downcase
45
- erb_file = render_view ? "#{render_view}" : "#{view_file_name}_#{@route[:action]}"
45
+ view_file_name = self.class.name.split('Controller').first.downcase
46
+ erb_file = render_view ? render_view.to_s : "#{view_file_name}_#{@route[:action]}"
46
47
  lib = Rubee::PROJECT_NAME == 'rubee' ? 'lib/' : ''
47
48
  view = render_template(erb_file, { object:, **(options[:locals] || {}) })
48
49
 
@@ -55,7 +56,7 @@ module Rubee
55
56
  ERB.new(view).result(binding)
56
57
  end
57
58
 
58
- return [status, headers.merge("content-type" => "text/html"), [whole_erb]]
59
+ [status, headers.merge('content-type' => 'text/html'), [whole_erb]]
59
60
  end
60
61
  end
61
62
 
@@ -69,25 +70,33 @@ module Rubee
69
70
 
70
71
  def params
71
72
  inputs = @request.env['rack.input'].read
72
- body = JSON.parse(@request.body.read.strip) rescue body = {}
73
- body.merge!(URI.decode_www_form(inputs).to_h.transform_keys(&:to_sym)) rescue nil
73
+ body = begin
74
+ JSON.parse(@request.body.read.strip)
75
+ rescue StandardError
76
+ {}
77
+ end
78
+ begin
79
+ body.merge!(URI.decode_www_form(inputs).to_h.transform_keys(&:to_sym))
80
+ rescue StandardError
81
+ nil
82
+ end
74
83
  @params ||= extract_params(@request.path, @route[:path])
75
84
  .merge(body)
76
85
  .merge(@request.params)
77
86
  .transform_keys(&:to_sym)
78
- .select { |k,v| ![:_method].include?(k.downcase.to_sym) }
87
+ .reject { |k, _v| [:_method].include?(k.downcase.to_sym) }
79
88
  end
80
89
 
81
90
  def headers
82
- @request.env.select {|k,v| k.start_with? 'HTTP_'}
83
- .collect {|key, val| [key.sub(/^HTTP_/, ''), val]}
91
+ @request.env.select { |k, _v| k.start_with?('HTTP_') }
92
+ .collect { |key, val| [key.sub(/^HTTP_/, ''), val] }
84
93
  end
85
94
 
86
95
  def extract_params(path, pattern)
87
96
  regex_pattern = pattern.gsub(/\{(\w+)\}/, '(?<\1>[^/]+)')
88
97
  regex = Regexp.new("^#{regex_pattern}$")
89
98
 
90
- if match = path.match(regex)
99
+ if (match = path.match(regex))
91
100
  return match.named_captures&.transform_keys(&:to_sym)
92
101
  end
93
102
 
@@ -18,37 +18,39 @@ module Rubee
18
18
  def authentificated?
19
19
  methods = self.class._auth_methods
20
20
  return true if methods && !methods.include?(@route[:action].to_sym)
21
+
21
22
  # This is suppose to be set in the middleware, otherwise it will return false
22
23
  valid_token?
23
24
  end
24
25
 
25
26
  def valid_token?
26
- @request.env["rack.session"]&.[]("authentificated")
27
+ @request.env['rack.session']&.[]('authentificated')
27
28
  end
28
29
 
29
30
  def authentificated_user
30
31
  # User model must be created with email and password properties at least
31
- @authehtificated_user ||= User.where(email: params[:email], password: params[:password]).first
32
+ @authentificated_user ||= User.where(email: params[:email], password: params[:password]).first
32
33
  end
33
34
 
34
35
  def authentificate!
35
36
  return false unless authentificated_user
37
+
36
38
  # Generate token
37
39
  payload = { username: params[:email], exp: Time.now.to_i + EXPIRE }
38
40
  @token = JWT.encode(payload, KEY, 'HS256')
39
41
  # Set jwt token to the browser within cookie, so next browser request will include it.
40
42
  # make sure it passed to response_with headers options
41
- @token_header = { "set-cookie" => "jwt=#{@token}; path=/; httponly; secure" }
43
+ @token_header = { 'set-cookie' => "jwt=#{@token}; path=/; httponly; secure" }
42
44
 
43
45
  true
44
46
  end
45
47
 
46
48
  def unauthentificate!
47
- @request.env["rack.session"]["authentificated"] = nil if @request.env["rack.session"]&.[]("authentificated")
49
+ @request.env['rack.session']['authentificated'] = nil if @request.env['rack.session']&.[]('authentificated')
48
50
  @authehtificated_user = nil if @authehtificated_user
49
51
  @zeroed_token_header = {
50
- "set-cookie" => "jwt=; path=/; httponly; secure; expires=thu, 01 jan 1970 00:00:00 gmt",
51
- "content-type" => "application/json"
52
+ 'set-cookie' => 'jwt=; path=/; httponly; secure; expires=thu, 01 jan 1970 00:00:00 gmt',
53
+ 'content-type' => 'application/json',
52
54
  }
53
55
 
54
56
  true
@@ -58,7 +60,7 @@ module Rubee
58
60
  if authentificated?
59
61
  yield
60
62
  else
61
- response_with type: :unauthentificated
63
+ response_with(type: :unauthentificated)
62
64
  end
63
65
  end
64
66
  end
@@ -69,7 +71,7 @@ module Rubee
69
71
  @auth_methods.concat(args.map(&:to_sym)).uniq!
70
72
 
71
73
  @auth_methods.each do |method|
72
- around method, :handle_auth
74
+ around(method, :handle_auth)
73
75
  end
74
76
  end
75
77
 
@@ -9,7 +9,7 @@ module Middlewarable
9
9
 
10
10
  module Initializer
11
11
  def initialize(req, route)
12
- app = ->(env) { super(req, route) }
12
+ app = ->(_env) { super(req, route) }
13
13
  self.class.middlewares.reverse_each do |middleware|
14
14
  middleware_class = Object.const_get(middleware)
15
15
  app = middleware_class.new(app, req)
@@ -7,13 +7,13 @@ module Rubee
7
7
 
8
8
  def call(env)
9
9
  # get token from header
10
- auth_header = headers(env)["HTTP_AUTHORIZATION"]
11
- token = auth_header ? auth_header[/^Bearer (.*)$/]&.gsub("Bearer ", "") : nil
10
+ auth_header = headers(env)['HTTP_AUTHORIZATION']
11
+ token = auth_header ? auth_header[/^Bearer (.*)$/]&.gsub('Bearer ', '') : nil
12
12
  # get token from cookies
13
- token = @req.cookies["jwt"] unless token
13
+ token ||= @req.cookies['jwt']
14
14
  if valid_token?(token)
15
- env["rack.session"] ||= {}
16
- env["rack.session"]["authentificated"] = true
15
+ env['rack.session'] ||= {}
16
+ env['rack.session']['authentificated'] = true
17
17
  end
18
18
 
19
19
  @app.call(env)
@@ -22,7 +22,7 @@ module Rubee
22
22
  private
23
23
 
24
24
  def headers(env)
25
- env.each_with_object({}) { |(k, v), h| h[k] = v if k.start_with?("HTTP_") }
25
+ env.each_with_object({}) { |(k, v), h| h[k] = v if k.start_with?('HTTP_') }
26
26
  end
27
27
 
28
28
  def valid_token?(token)
@@ -35,8 +35,12 @@ module Rubee
35
35
  end
36
36
 
37
37
  def decode_jwt(token)
38
- decoded_array = JWT.decode(token, AuthTokenable::KEY, true, { algorithm: 'HS256' }) rescue decoded_array = []
39
- decoded_array&.first&.transform_keys(&:to_sym) || {} # Extract payload
38
+ decoded_array = begin
39
+ JWT.decode(token, AuthTokenable::KEY, true, { algorithm: 'HS256' })
40
+ rescue StandardError
41
+ []
42
+ end
43
+ decoded_array&.first&.transform_keys(&:to_sym) || {} # Extract payload
40
44
  end
41
45
  end
42
46
  end
@@ -16,7 +16,7 @@ module Rubee
16
16
  super(*args, &block)
17
17
  end
18
18
  end
19
- prepend hooks
19
+ prepend(hooks)
20
20
  end
21
21
 
22
22
  def after(method, handler, **options)
@@ -31,7 +31,7 @@ module Rubee
31
31
  result
32
32
  end
33
33
  end
34
- prepend hooks
34
+ prepend(hooks)
35
35
  end
36
36
 
37
37
  def around(method, handler, **options)
@@ -48,7 +48,7 @@ module Rubee
48
48
  end
49
49
  end
50
50
  end
51
- prepend hooks
51
+ prepend(hooks)
52
52
  end
53
53
  end
54
54
 
@@ -58,7 +58,6 @@ module Rubee
58
58
  def conditions_met?(if_condition = nil, unless_condition = nil)
59
59
  return true if if_condition.nil? && unless_condition.nil?
60
60
 
61
- if_condition_result = true
62
61
  if_condition_result =
63
62
  if if_condition.nil?
64
63
  true
@@ -67,8 +66,6 @@ module Rubee
67
66
  elsif respond_to?(if_condition)
68
67
  send(if_condition)
69
68
  end
70
-
71
- unless_condition_result = true
72
69
  unless_condition_result =
73
70
  if unless_condition.nil?
74
71
  false
@@ -8,19 +8,19 @@ module Rubee
8
8
  module Initializer
9
9
  def initialize(attrs)
10
10
  attrs.each do |attr, value|
11
- self.send("#{attr}=", value)
11
+ send("#{attr}=", value)
12
12
  end
13
13
  end
14
14
  end
15
15
 
16
16
  module InstanceMethods
17
- def to_json
17
+ def to_json(*_args)
18
18
  to_h.to_json
19
19
  end
20
20
 
21
21
  def to_h
22
22
  instance_variables.each_with_object({}) do |var, hash|
23
- hash[var.to_s.delete("@")] = instance_variable_get(var)
23
+ hash[var.to_s.delete('@')] = instance_variable_get(var)
24
24
  end
25
25
  end
26
26
  end
@@ -1,32 +1,32 @@
1
1
  module Rubee
2
2
  module DatabaseObjectable
3
3
  def self.included(base)
4
- base.extend ClassMethods
5
- base.include InstanceMethods
6
- base.prepend Initializer
4
+ base.extend(ClassMethods)
5
+ base.include(InstanceMethods)
6
+ base.prepend(Initializer)
7
7
 
8
- base.include Rubee::Hookable
9
- base.include Rubee::Serializable
8
+ base.include(Rubee::Hookable)
9
+ base.include(Rubee::Serializable)
10
10
  end
11
11
 
12
12
  module ClassMethods
13
13
  def pluralize_class_name
14
- pluralize(self.name.downcase)
14
+ pluralize(name.downcase)
15
15
  end
16
16
 
17
17
  def pluralize(word)
18
18
  if word.end_with?('y') && !%w[a e i o u].include?(word[-2])
19
- word[0..-2] + 'ies' # Replace "y" with "ies"
19
+ "#{word[0..-2]}ies" # Replace "y" with "ies"
20
20
  elsif word.end_with?('s', 'x', 'z', 'ch', 'sh')
21
- word + 'es' # Add "es" for certain endings
21
+ "#{word}es" # Add "es" for certain endings
22
22
  else
23
- word + 's' # Default to adding "s"
23
+ "#{word}s" # Default to adding "s"
24
24
  end
25
25
  end
26
26
 
27
27
  def singularize(word)
28
28
  if word.end_with?('ies') && word.length > 3
29
- word[0..-4] + 'y' # Convert "ies" to "y"
29
+ "#{word[0..-4]}y" # Convert "ies" to "y"
30
30
  elsif word.end_with?('es') && %w[s x z ch sh].any? { |ending| word[-(ending.length + 2)..-3] == ending }
31
31
  word[0..-3] # Remove "es" for words like "foxes", "buses"
32
32
  elsif word.end_with?('s') && word.length > 1
@@ -38,7 +38,7 @@ module Rubee
38
38
 
39
39
  def accessor_names
40
40
  instance_methods(false)
41
- .select { |m| method_defined?("#{m}=") } # Check if setter exists
41
+ .select { |m| method_defined?("#{m}=") } # Check if setter exists
42
42
  end
43
43
  end
44
44
 
@@ -49,4 +49,3 @@ module Rubee
49
49
  end
50
50
  end
51
51
  end
52
-
@@ -2,7 +2,7 @@ module Rubee
2
2
  class SequelObject
3
3
  include Rubee::DatabaseObjectable
4
4
 
5
- def destroy(cascade: false, **options)
5
+ def destroy(cascade: false, **_options)
6
6
  if cascade
7
7
  # find all tables with foreign key
8
8
  tables_with_fk = DB.tables.select do |table|
@@ -23,26 +23,25 @@ module Rubee
23
23
  if args[:id]
24
24
  begin
25
25
  udpate(args)
26
- rescue => _
26
+ rescue StandardError => _e
27
27
  return false
28
28
  end
29
29
 
30
- true
31
30
  else
32
31
  begin
33
32
  created_object = self.class.create(args)
34
- rescue => _
33
+ rescue StandardError => _e
35
34
  return false
36
35
  end
37
36
  self.id = created_object.id
38
37
 
39
- true
40
38
  end
39
+ true
41
40
  end
42
41
 
43
- def assign_attributes(args={})
44
- to_h.each do |attr, value|
45
- self.send("#{attr}=", args[attr.to_sym]) if args[attr.to_sym]
42
+ def assign_attributes(args = {})
43
+ to_h.each_key do |attr|
44
+ send("#{attr}=", args[attr.to_sym]) if args[attr.to_sym]
46
45
  end
47
46
  end
48
47
 
@@ -65,14 +64,14 @@ module Rubee
65
64
  class << self
66
65
  def last
67
66
  found_hash = dataset.order(:id).last
68
- return self.new(**found_hash) if found_hash
67
+ return new(**found_hash) if found_hash
69
68
 
70
69
  nil
71
70
  end
72
71
 
73
72
  def first
74
73
  found_hash = dataset.order(:id).first
75
- return self.new(**found_hash) if found_hash
74
+ return new(**found_hash) if found_hash
76
75
 
77
76
  nil
78
77
  end
@@ -81,9 +80,9 @@ module Rubee
81
80
  # owns_many :comments
82
81
  # > user.comments
83
82
  # > [<comment1>, <comment2>]
84
- def owns_many(assoc, fk_name: nil, over: nil, **options)
83
+ def owns_many(assoc, fk_name: nil, over: nil, **_options)
85
84
  singularized_assoc_name = singularize(assoc.to_s)
86
- fk_name ||= "#{self.name.to_s.downcase}_id"
85
+ fk_name ||= "#{name.to_s.downcase}_id"
87
86
 
88
87
  define_method(assoc) do
89
88
  klass = Object.const_get(singularized_assoc_name.capitalize)
@@ -102,9 +101,9 @@ module Rubee
102
101
  # owns_one :user
103
102
  # > comment.user
104
103
  # > <user>
105
- def owns_one(assoc, options={})
104
+ def owns_one(assoc, options = {})
106
105
  Sequel::Model.one_to_one(assoc, **options)
107
- fk_name ||= "#{self.name.to_s.downcase}_id"
106
+ fk_name ||= "#{name.to_s.downcase}_id"
108
107
  define_method(assoc) do
109
108
  Object.const_get(assoc.capitalize).where(fk_name.to_sym => id)&.first
110
109
  end
@@ -114,11 +113,11 @@ module Rubee
114
113
  # holds :user
115
114
  # > account.user
116
115
  # > <user>
117
- def holds(assoc, fk_name: nil, **options)
116
+ def holds(assoc, fk_name: nil, **_options)
118
117
  fk_name ||= "#{assoc.to_s.downcase}_id"
119
118
  define_method(assoc) do
120
119
  target_klass = Object.const_get(assoc.capitalize)
121
- target_klass.find(self.send(fk_name))
120
+ target_klass.find(send(fk_name))
122
121
  end
123
122
  end
124
123
 
@@ -130,33 +129,33 @@ module Rubee
130
129
 
131
130
  def dataset
132
131
  @dataset ||= DB[pluralize_class_name.to_sym]
133
- rescue Exception => _
132
+ rescue Exception => _e
134
133
  reconnect!
135
134
  retry
136
135
  end
137
136
 
138
137
  def all
139
138
  dataset.map do |record_hash|
140
- self.new(**record_hash)
139
+ new(**record_hash)
141
140
  end
142
141
  end
143
142
 
144
143
  def find(id)
145
144
  found_hash = dataset.where(id:)&.first
146
- return self.new(**found_hash) if found_hash
145
+ return new(**found_hash) if found_hash
147
146
 
148
147
  nil
149
148
  end
150
149
 
151
150
  def where(args)
152
151
  dataset.where(**args).map do |record_hash|
153
- self.new(**record_hash)
152
+ new(**record_hash)
154
153
  end
155
154
  end
156
155
 
157
156
  def order(*args)
158
157
  dataset.order(*args).map do |record_hash|
159
- self.new(**record_hash)
158
+ new(**record_hash)
160
159
  end
161
160
  end
162
161
 
@@ -166,18 +165,18 @@ module Rubee
166
165
 
167
166
  def create(attrs)
168
167
  out_id = dataset.insert(**attrs)
169
- self.new(**(attrs.merge(id: out_id)))
168
+ new(**attrs.merge(id: out_id))
170
169
  end
171
170
 
172
171
  def destroy_all(cascade: false)
173
- all.each{ |record| record.destroy(cascade:) }
172
+ all.each { |record| record.destroy(cascade:) }
174
173
  end
175
174
 
176
175
  def serialize(suquel_dataset, klass = nil)
177
176
  klass ||= self
178
177
  suquel_dataset.map do |record_hash|
179
178
  target_klass_fields = DB[pluralize(klass.name.downcase).to_sym].columns
180
- klass_attributes = record_hash.filter{ target_klass_fields.include? _1 }
179
+ klass_attributes = record_hash.filter { target_klass_fields.include?(_1) }
181
180
  klass.new(**klass_attributes)
182
181
  end
183
182
  end