-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrails_general_notes.txt
1046 lines (658 loc) · 27.2 KB
/
rails_general_notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Rails Notes (rails command and rake)
===============================================================================
- https://github.com/rohandaxini/rails-concepts-topics
1. What are all naming conventions I need to be aware of?
db table is plural,
model is singular,
controller is plural.
so you have the User model that is backed by the users table, and visible through the UsersController.
files should be named as the wide_cased version of the class name.
so the FooBar class needs to be in a file called foo_bar.rb.
If you are namespacing with modules, the namespaces need to be represented by folders.
so if we are talking about Foo::Bar class, it should be in foo/bar.rb.
2. How should controller actions be structured and named?
Controller actions should be RESTful.
That means that you should think of your controllers as exposing a resource, not as just enabling RPCs.
Rails has a concept of member actions vs collection actions for resources.
- A member action is something that operates on a specific instance, for example /users/1/edit would be an edit member action for users.
- A collection action is something that operates on all the resources. So /users/search?name=foo would be a collection action.
The tutorials above describe how to actually implement these ideas in your routes file.
3. What are the best ways to render information in a view (via :content_for or render a partial) and what are ways I shouldn't use?
content_for should be used when you want to be able to append html from an inner template to an outer template
-- for example, being able to append something from your view template into your layout template.
A good example would be to add a page specific javascript.
# app/views/layout/application.rb
<html>
<head>
<%= yield :head %>
...
# app/views/foobars/index.html.erb
<% content_for :head do %>
<script type='text/javascript'>
alert('zomg content_for!');
</script>
<% end %>
partials are either for breaking up large files, or for rendering the same bit of information multiple times. For example
<table>
<%= render :partial => 'foo_row', :collection => @foobars %>
</table>
# _foo_row.html.erb
<tr>
<td>
<%= foobar.name %>
</td>
</tr>
4.What should go into a helper and what shouldn't?
your templates should only have basic branching logic in them.
If you need to do anything more intense, it should be in a helper.
local variables in views are an abomination against all that is good and right in the world, so that is a great sign that you should make a helper.
Another reason is just pure code reuse.
If you are doing the same thing with only slight variation over and over again, pull it into a helper (if it is the exact same thing, it should be in a partial).
5. What are common pitfalls or something I need to do correctly from the very beginning?
partials should never refer directly to instance (@) variables, since it will prevent re-use down the line.
Always pass data in via the :locals => { :var_name => value } param to the render function.
Keep logic out of your views that is not directly related to rendering your views.
If you have the option to do something in the view, and do it somewhere else, 9 times out of 10 doing it somewhere else is the better option.
We have a mantra in rails that is "fat models, skinny controllers".
- One reason is that models are object oriented, controllers are inherantly procedural.
- Another is that models can cross controllers, but controllers cant cross models.
- A third is that models are more testable. Its just a good idea.
6. How can you modularize code? Is that what the lib folder is for?
the lib folder is for code that crosses the concerns of models (i.e. something that isn't a model, but will be used by multiple models).
When you need to put something in there, you will know, because you wont be able to figure out what model to put it in. Until that happens, you can just ignore lib.
Something to keep in mind is that as of rails 3,
lib is not on the autoload path, meaning that you need to require anything you put in there (or add it back in)
A way to automatically require all modules in the lib directory:
#config/initializers/requires.rb
Dir[File.join(Rails.root, 'lib', '*.rb')].each do |f|
require f
end
Rails Components
========================================================================
Action Pack
------------
# https://guides.rubyonrails.org/action_controller_overview.html
- Action Pack is a framework for handling and responding to web requests.
- It provides mechanisms for routing (mapping request URLs to actions), defining controllers that implement actions, and generating responses.
- In short, Action Pack provides the controller layer in the MVC paradigm.
- It consists of several modules:
- Action Dispatch, which parses information about the web request, handles routing as defined by the user, and does advanced processing related to HTTP such as MIME-type negotiation, decoding parameters in POST, PATCH, or PUT bodies, handling HTTP caching logic, cookies and sessions.
- Action Controller, which provides a base controller class that can be subclassed to implement filters and actions to handle requests. The result of an action is typically content generated from views.
ActionCable
------------
# Check https://docs.anycable.io for production performance engine
- Action Cable seamlessly integrates WebSockets with the rest of your Rails application.
- It allows for real-time features to be written in Ruby in the same style and form as the rest of your Rails application, while still being performant and scalable.
- It's a full-stack offering that provides both a client-side JavaScript framework and a server-side Ruby framework.
- You have access to your entire domain model written with Active Record or your ORM of choice.
ActiveSupport
-------------
- Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
# https://guides.rubyonrails.org/v3.2/active_support_core_extensions.html
require 'active_support/all'
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/hash"
# permits access to the keys as either strings or symbols.
{a: 1}.with_indifferent_access["a"] # => 1
#
blank? and present?
nil and false,
strings composed only of whitespace (see note below),
empty arrays and hashes, and
any other object that responds to empty? and is empty.
host = config[:host].presence || 'localhost'
"foo".dup # => "foo"
"".dup # => ""
Rational(1).dup # => (1/1)
Complex(0).dup # => (0+0i)
1.method(:+).dup # => TypeError (allocator undefined for Method)
"foo".duplicable? # => true
"".duplicable? # => true
Rational(1).duplicable? # => true
Complex(1).duplicable? # => true
1.method(:+).duplicable? # => false
array.deep_dup # including other objects (strings) unlike dup
@number.try(:next)
@person.try { |p| "#{p.first_name} #{p.last_name}" }
@number.try(:nest) # => nil
@number.try!(:nest) # NoMethodError: undefined method `nest' for 1:Integer
class_eval(*args, &block)
some_klass.acts_like?(:string)
7.to_param # => "7"
"Tom & Jerry".to_param # => "Tom & Jerry"
[0, true, String].to_param # => "0/true/String"
class User
def to_param
"#{id}-#{name.parameterize}"
end
end
user_path(@user) # => "/users/357-john-smith"
current_user.to_query('user') # => "user=357-john-smith"
account.to_query('company[name]')
# => "company%5Bname%5D=Johnson+%26+Johnson"
[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
{c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
{id: 89, name: "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
class Account < ApplicationRecord
with_options dependent: :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
assoc.has_many :invoices
assoc.has_many :expenses
end
end
I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
subject i18n.t :subject
body i18n.t :body, user_name: user.name
end
- JSON support
- INstance variables
class C
def initialize(x, y)
@x, @y = x, y
end
end
C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
C.new(0, 1).instance_variable_names # => ["@x", "@y"]
- Slience Warning
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
# If the user is locked, the increment is lost, no big deal.
suppress(ActiveRecord::StaleObjectError) do
current_user.increment! :visits
end
- In?
1.in?([1,2]) # => true
"lo".in?("hello") # => true
25.in?(30..50) # => false
1.in?(1) # => ArgumentError
- Alias
class User < ApplicationRecord
# You can refer to the email column as "login".
# This can be meaningful for authentication code.
alias_attribute :login, :email
end
- internal Attr
# library
class ThirdPartyLibrary::Crawler
attr_internal :log_level
end
- Class Attrs
class A
class_attribute :x
end
class B < A; end
class C < B; end
A.x = :a
B.x # => :a
C.x # => :a
B.x = :b
A.x # => :a
C.x # => :b
- subclasses (one level) & descendants ( all levels)
class C; end
C.subclasses # => []
class B < C; end
C.subclasses # => [B]
- String
"".html_safe? # => false
<%= @review.title %> <%# fine, escaped if needed %>
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %> <%== @cms.current_template %> <%# inserts @cms.current_template as is %>
"Hello World".remove(/Hello /) # => "World"
" \n foo\n\r \t bar \n".squish # => "foo bar"
"Oh dear! Oh dear! I shall be late!".truncate(20)
"Oh dear! Oh dear! I shall be late!".truncate(20, omission: '…')
"Oh dear! Oh dear! I shall be late!".truncate(18, separator: ' ')
"👍👍👍👍".truncate_bytes(15)
"👍👍👍👍".truncate_bytes(15, omission: "🖖")
"Oh dear! Oh dear! I shall be late!".truncate_words(4)
"Oh dear! Oh dear! I shall be late!".truncate_words(4, omission: '…')
"production".inquiry.production? # => true
"active".inquiry.inactive? # => false
"foo".starts_with?("f") # => true
"foo".ends_with?("o") # => true
# skip indetnations
if options[:usage]
puts <<-USAGE.strip_heredoc
This command does such and such.
Supported options are:
-h This message
...
USAGE
end
# or add identiation
<<EOS.indent(2)
def some_method
some_code
end
EOS
" foo".indent(2) # => " foo"
"hello".at(4) # => "o"
"hello".from(2) # => "llo"
"hello".to(-2) # => "hell"
"hello".first # h
"hello".last # o
"table".pluralize # => "tables"
"equipment".pluralize # => "equipment"
"dude".pluralize(1) # => "dude"
"dude".pluralize(2) # => "dudes"
# active_record/model_schema.rb
def undecorated_table_name(model_name)
table_name = model_name.to_s.demodulize.underscore
pluralize_table_names ? table_name.pluralize : table_name
end
"tables".singularize # => "table"
# active_record/reflection.rb
def derive_class_name
class_name = name.to_s.camelize
class_name = class_name.singularize if collection?
class_name
end
"backoffice/session".camelize # => "Backoffice::Session"
"visual_effect".camelize(:lower) # => "visualEffect"
"AdminUser".underscore # => "admin_user"
"SomeController".delete_suffix("Controller").underscore # some
"BigSomeController".delete_suffix("Controller").underscore # big_some
"alice in wonderland".titleize # => "Alice In Wonderland"
"contact_data".dasherize # => "contact-data"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
"Backoffice::UsersController".deconstantize # => "Backoffice"
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
"Kurt Gödel".parameterize # => "kurt-godel"
"John Smith".parameterize(preserve_case: true) # => "John-Smith"
"John Smith".parameterize(separator: "_") # => "john\_smith"
"InvoiceLine".tableize # => "invoice_lines"
"invoice_lines".classify # => "InvoiceLine"
"highrise_production.companies".classify # => "Company"
# Constant name resolution by constantize starts always at the top-level Object even if there is no leading "::".
"Integer".constantize # => Integer
module M
X = 1
end
"M::X".constantize # => 1
"author_id".humanize(capitalize: false) # => "author"
"comments_count".humanize # => "Comments count"
"author_id".humanize # => "Author"
"User".foreign_key
"Admin::Session".foreign_key # => "session_id"
"InvoiceLine".foreign_key # => "invoice_line_id"
"User".foreign_key(false) # => "userid"
- Conversions
"2010-07-27".to_date # => Tue, 27 Jul 2010
"2010-07-27 23:37:00".to_time # => 2010-07-27 23:37:00 +0200
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
"2010-07-27 23:42:00".to_time(:utc) # => 2010-07-27 23:42:00 UTC
"2010-07-27 23:42:00".to_time(:local) # => 2010-07-27 23:42:00 +0200
:foo.starts_with?("f") # => true
:foo.ends_with?("o") # => true
- Numeric
2.kilobytes # => 2048
3.megabytes # => 3145728
3.5.gigabytes # => 3758096384
-4.exabytes # => -4611686018427387904
- Time
# equivalent to Time.current.advance(days: 1)
1.day.from_now
# equivalent to Time.current.advance(weeks: 2)
2.weeks.from_now
# equivalent to Time.current.advance(days: 4, weeks: 5)
(4.days + 5.weeks).from_now
# equivalent to Time.current.advance(months: 1)
1.month.from_now
# equivalent to Time.current.advance(years: 2)
2.years.from_now
# equivalent to Time.current.advance(months: 4, years: 5)
(4.months + 5.years).from_now
- phone
5551234.to_fs(:phone)
# => 555-1234
1235551234.to_fs(:phone)
# => 123-555-1234
1235551234.to_fs(:phone, area_code: true)
# => (123) 555-1234
1235551234.to_fs(:phone, delimiter: " ")
# => 123 555 1234
1235551234.to_fs(:phone, area_code: true, extension: 555)
# => (123) 555-1234 x 555
1235551234.to_fs(:phone, country_code: 1)
# => +1-123-555-1234
- currency
1234567890.50.to_fs(:currency) # => $1,234,567,890.50
1234567890.506.to_fs(:currency) # => $1,234,567,890.51
1234567890.506.to_fs(:currency, precision: 3) # => $1,234,567,890.506
2.multiple_of?(1) # => true
1.ordinal # => "st"
2.ordinal # => "nd"
53.ordinal # => "rd"
2009.ordinal # => "th"
-21.ordinal # => "st"
-134.ordinal # => "th"
1.ordinalize # => "1st"
2.ordinalize # => "2nd"
53.ordinalize # => "53rd"
2009.ordinalize # => "2009th"
-21.ordinalize # => "-21st"
-134.ordinalize # => "-134th"
BigDecimal(5.00, 6).to_s # => "5.0"
BigDecimal(5.00, 6).to_s("e") # => "0.5E1"
[1, 2, 3].sum # => 6
(1..100).sum # => 5050
(1..5).sum {|n| n * 2 } # => 30
[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
%w(foo bar baz).sum # => "foobarbaz"
{a: 1, b: 2, c: 3}.sum # => [:a, 1, :b, 2, :c, 3]
- index_with
invoices.index_by(&:number) # => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
%i( title body ).index_with { |attr_name| post.public_send(attr_name) }
# => { title: "hey there", body: "what's up?" }
WEEKDAYS.index_with(Interval.all_day)
# => { monday: [ 0, 1440 ], … }
- many
<% if pages.many? %>
<%= pagination_links %>
<% end %>
to_visit << node if visited.exclude?(node)
[ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ]
["David", "Rafael"].including %w[ Aaron Todd ] # => ["David", "Rafael", "Aaron", "Todd"]
["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"]
[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) # => ["David", "Rafael", "Aaron"]
[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name) # => [[1, "David"], [2, "Rafael"]]
[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name) # => "David"
[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pick(:id, :name) # => [1, "David"]
- Arrays
%w(a b c d).to(2) # => ["a", "b", "c"]
[].to(7) # => []
%w(a b c d).from(2) # => ["c", "d"]
%w(a b c d).from(10) # => []
[].from(0) # => []
[ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ]
[ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ]
["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"]
[ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ])
actionmailbox (7.0.1)
actionmailer (7.0.1)
actiontext (7.0.1)
actionview (7.0.1)
activejob (7.0.1)
activemodel (7.0.1)
activerecord (7.0.1)
activestorage (7.0.1)
rails (7.0.1)
railties (7.0.1)
Service Objects
------------------------------------------------------------------------
# app/services/twitter_service.rb
module TwitterService
def self.send_welcome_message(twitter_handle)
client.update("@#{twitter_handle} welcome to 'Oranges & Apples', we hope you enjoy our juicy fruit!")
end
def self.client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.access_token = "..."
config.access_token_secret = "..."
end
end
end
- your controller
class UsersController
def create
# ...
TwitterService.send_welcome_message(user.twitter_handle)
end
end
------
app/services/tweet_creator.rb
# app/services/tweet_creator.rb
class TweetCreator
def initialize(message)
@message = message
end
def send_tweet
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_SECRET']
end
client.update(@message)
end
end
TweetCreator.new(params[:message]).send_tweet
Proccall invokes the block, setting the block’s parameters to the values in params using something close to method calling semantics. It returns the value of the last expression evaluated in the block.
aproc = Proc.new {|scalar, values| values.map {|value| valuescalar } }
aproc.call(9, 1, 2, 3) #=> [9, 18, 27]
aproc[9, 1, 2, 3] #=> [9, 18, 27]
aproc.(9, 1, 2, 3) #=> [9, 18, 27]
aproc.yield(9, 1, 2, 3) #=> [9, 18, 27]
So let’s make our service object behave more like a proc!
# app/services/application_service.rb
class ApplicationService
def self.call(*args, &block)
new(*args, &block).call
end
end
.. then
# app/services/tweet_creator.rb
class TweetCreator < ApplicationService
attr_reader :message
def initialize(message)
@message = message
end
def call
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_SECRET']
end
client.update(@message)
end
end
class TweetController < ApplicationController
def create
TweetCreator.call(params[:message])
end
end
Make lib autploaded
------------------------------------------------------------------------
application.rb
config.autoload_paths << "#{Rails.root}/lib"
# https://codeburst.io/ruby-on-rails-concepts-explained-with-real-world-use-cases-588dc85d8e96
trailblazer
====================================================================================
The Advanced Business Logic Framework
https://trailblazer.to/2.0/index.html
Notes:
================
Maybe it will help to enable SQL logging and see if the correct data is sent to the database?
ActiveRecord::Base.logger = Logger.new(STDOUT). – shock_one Feb 10 '15 at 21:04
References
==========
- https://github.com/markets/awesome-ruby
Translations
========================================================================
https://github.com/glebm/i18n-tasks
https://github.com/Sage/i18n_yaml_editor
> gem install i18n_yaml_editor
> i18n_yaml_editor path/to/i18n/locales [port]
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Notes:
================
Maybe it will help to enable SQL logging and see if the correct data is sent to the database?
ActiveRecord::Base.logger = Logger.new(STDOUT). – shock_one Feb 10 '15 at 21:04
References
==========
- https://github.com/markets/awesome-ruby
Design Patterns
=====================================================================================
- Factory
Class that has one creation method with a large conditional.
- Form object
Move form-specific logic away from your ActiveRecord models into a separate class.
Submitting form data is a common feature of web applications – allowing users to submit their information and giving them feedback whether the information is valid or not.
ActiveRecord comes with a powerful set of validators for attributes on a persisted data model. When data is not persisted, or used for other non-active record purposes, Active Model Helper Modules reduce the complexity of validations on your plain old Ruby objects.
- Routing
---------
Create the routes needed for displaying the form object and posting the data
Restrict resources to the routes you need using only:
# config/routes.rb
resources :registration, only: [:new, :create]
- Controller and Actions
------------------------
Create a controller with new and create actions.
respond_with will re-render the new action if there are any validation errors on the model
If there are no errors on the model the visitor will be redirected to show the current resource. In this case the user will be redirected to some_other_success_path
# app/controllers/registration_controller.rb
class RegistrationsController < ApplicationController
respond_to :html
def new
@registration = Registration.new
end
def create
@registration = Registration.new(registration_params)
@registration.register
respond_with @registration, location: some_success_path
end
private
def registration_params
# ...
end
end
- View with Registration Form
------------------------------
The view renders a web form with fields to submit.
Use the ActiveModel object @registration in the form
Form generates the endpoint registration_path and method of delivery post
Validation errors will display inline within the form just like ActiveRecord
# app/views/registration/new.html.erb
<%= form_for @registration do |f| %>
<%= f.label :first_name, 'First Name' %>:
<%= f.text_field :first_name %>
...
<%= f.submit %>
<% end %>
- Object with ActiveModel Conversion, Naming, and Validations
-------------------------------------------------------------
Use any of the ActiveRecord Validations in the model.
Command pattern used when calling register method.
ActiveRecord validation syntax on attributes.
ActiveModel::Model mixin includes modules, and includes an initialization method.
# app/models/registration.rb
class Registration
include ActiveModel::Model
attr_accessor(
:company_name,
:email,
:first_name,
:last_name,
:terms_of_service
)
validates :company_name, presence: true
validates :email, presence: true, email: true
validates :first_name, presence: true
validates :last_name, presence: true
validates :terms_of_service, acceptance: true
def register
if valid?
# Do something interesting here
# - create user
# - send notifications
# - log events, etc.
end
end
private
def create_user
# ...
end
end
- Value object
A small simple object, like a date range or location, whose equality isn’t based on identity.
<=>, hash, and eql? which allow us to make use of operations like sort and uniq. We get the following usage:
- Null object
Instead of returning null, or some odd value, return a Special Case that has the same interface as what the caller expects.
- Query object
Represent a database query or a set of database queries related to the same table.
# https://medium.flatstack.com/query-object-in-ruby-on-rails-56ea434365f0
- Service object
Concentrate the core logic of a request operation into a separate object.
# http://brewhouse.io/blog/2014/04/30/gourmet-service-objects.html
A service object does one thing
A service object (aka method object) performs one action. It holds the business logic to perform that action. Here is an example:
class Invite < ActiveRecord::Base
def accept!(user, time=Time.now)
update_attributes!(
accepted_by_user_id: user.id,
accepted_at: time
)
end
end
# app/services/accept_invite.rb
class AcceptInvite
def self.call(invite, user)
invite.accept!(user)
UserMailer.invite_accepted(invite).deliver
end
end
.. then
class InviteController < ApplicationController
def accept
invite = Invite.find_by_token!(params[:token])
if AcceptInvite.call(invite, current_user)
redirect_to invite.item, notice: "Welcome!"
else
redirect_to '/', alert: "Oopsy!"
end
end
end
- Decorators used in rails ...
Background Jobs
========================================================================
- delayed_job
- Sidekiq : https://github.com/mperham/sidekiq
Some Handy Gems
========================================================================
Process management / puma / passenger / and cloud stuff ..... with nginx
========================================================================
nginx
======
> rails s =p 3005
nginx:
server {
listen 443;
ssl on;
ssl_certificate /data/opt/nginx/conf/ssl/bundle.crt;
ssl_certificate_key /data/opt/nginx/conf/ssl/d1g_com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
server_name www.d1g.com yasater.d1g.com hasnaa.d1g.com .d1g.com *.d1g.com d1g.com;
rewrite ^/photos(.*)$ https://www.yasater.com/photos$1 last;
rewrite ^/(.*)$ https://www.yasater.com/$1 redirect;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404;
proxy_pass http://127.0.0.1:3005;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
}
Missing `secret_key_base` for 'production' environment
RAILS_ENV=production rake secret -->
prodcuction.rb
config.secret_key_base = "1104db7a0342fc8b1f65c683681270b15f115bdf1477823ebe92b9ea10bcd0827b15e23db168c41ddcbd463986d0e8d72f8c5d0e0aac16827e8df093e15873a3"
Caching: