Best ruby questions in July 2011

Should one minify server code when it's in production?

23 votes

When it comes to the frontend code you always minify it (remove white spaces, comments etc) in production.

Should one do the same with server code? I usually have a lot of comments in my server files. But I have never heard about people doing so.

Wouldn't the server run faster if the code was optimized in the same way?

You're not going to have any improvement as the whitespaces and all formatting are lost when your server side code is translated to machine code (or interpreted). It's also not sent over the wire, it's read from the local filesystem, so while having less characters would lead to a faster startup, it would not make any difference on the long run and the startup speed gain would be marginal (or even unnoticeable).

So, no, minifying your server side code is basically useless, worse, it's probably going to make stack traces completely useless, as there's going to be a lot of code in the same line (and not necessarily with the same formatting you used).

Is string interning really useful?

11 votes

I was having a conversation about strings and various languages a while back, and the topic of string interning came up. Apparently Java and the .NET framework do this automatically with all strings, as well as several scripting languages. Theoretically, it saves memory because you don't end up with multiple copies of the same string, and it saves time because string equality comparisons are a simple pointer comparison instead of an O(N) run through each character of the string.

But the more I think about it, the more skeptical I grow of the concept's benefits. It seems to me that the advantages are mostly theoretical:

  • First off, to use automatic string interning, all strings must be immutable, which makes a lot of string processing tasks harder than they need to be. (And yes, I've heard all the arguments for immutability in general. That's not the point.)
  • Every time a new string is created, it has to be checked against the string interning table, which is at least a O(N) operation. (EDIT: Where N is the size of the string, not the size of the table, since this was confusing people.) So unless the ratio of string equality comparisons to new string creation is pretty high, it's unlikely that the net time saved is a positive value.
  • If the string equality table uses strong references, the strings will never get garbage collected when they're no longer needed, thus wasting memory. On the other hand, if the table uses weak references, then the string class requires some sort of finalizer to remove the string from the table, thus slowing down the GC process. (Which could be pretty significant, depending on how the string intern table is implemented. Worst case, deleting an item from a hash table can require an O(N) rebuild of the entire table under certain circumstances.)

This is just the result of me thinking about implementation details. Is there something I've missed? Does string interning actually provide any significant benefits in the general case?

EDIT 2: All right, apparently I was operating from a mistaken premise. The person I was talking to never pointed out that string interning was optional for newly-created strings, and in fact gave the strong impression that the opposite was true. Thanks to Jon for setting the matter straight. Another accepted answer for him.

No, Java and .NET don't do it "automatically with all strings". They (well, Java and C#) do it with constant string expressions expressed in bytecode/IL, and on demand via the String.intern and String.Intern (.NET) methods. The exact situation in .NET is interesting, but basically the C# compiler will guarantee that every reference to an equal string constant within an assembly ends up referring to the same string object. That can be done efficiently at type initialization time, and can save a bunch of memory.

It doesn't happen every time a new string is created.

(On the string immutability front, I for one am extremely glad that strings are immutable. I don't want to have to take a copy every time I receive a parameter etc, thank you very much. I haven't seen it make string processing tasks harder, either...)

And as others have pointed out, looking up a string in a hash table isn't generally an O(n) operation, unless you're incredibly unlucky with hash collisions...

Personally I don't use string interning in user-land code; if I want some sort of cache of strings I'll create a HashSet<string> or something similar. That can be useful in various situations where you expect to come across the same strings several times (e.g. XML element names) but with a simple collection you don't pollute a system-wide cache.

Mystifying "undefined constant" issue with Ruby/Rails

11 votes

I've got a Rails project where a constant is being nuked at some point while serving a request.

I'm using the mime/types and restclient gems. The restclient module defines an extension to MIME which contains the method type_for_extension.

module RestClient
    ...
    def stringify_headers headers
      result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
      ...
    end
  end
end

module MIME
  class Types
    def type_for_extension ext
      candidates = @extension_index[ext]
      candidates.empty? ? ext : candidates[0].content_type
    end
    class << self
      def type_for_extension ext
        @__types__.type_for_extension ext
      end
    end
  end
end

I can access MIME::Types.type_for_extension on my first invocation of a given controller action. On the second invocation, it's gone.

I can still use MIME::Types.type_for, but the added method is simply gone, so when I try to use the RestClient module it throws an exception on the line showin in stringify_headers:

NoMethodError, message: undefined method `type_for_extension' for MIME::Types:Class

**How is this possible? type_for_extension defined in the same file as stringify_headers; how could the latter get nuked but not the former?


EDIT: FIXED IT!

In my config:

config.gem "aws-s3", :version => ">= 0.6.2", :lib => "aws/s3"  
config.gem 'mime-types', :lib => 'mime/types'

aws-s3 was loading mime-types via require_library_or_gem, which ultimate invoked ActiveSupport::Dependencies.autoload_module! which maintains a table called autoloaded_constants which are nuked when ActionController.close calls Dispatcher.cleanup_application.

Fix was to load mime-types first, so it's not autoloaded.

*whew*

Answering my own question by request.

In my config:

config.gem "aws-s3", :version => ">= 0.6.2", :lib => "aws/s3"  
config.gem 'mime-types', :lib => 'mime/types'

aws-s3 library was loading mime-types via require_library_or_gem, which ultimately invoked ActiveSupport::Dependencies.autoload_module! which maintains a table called autoloaded_constants which are nuked when ActionController.close calls Dispatcher.cleanup_application.

Fix was to load mime-types first, so it's not autoloaded.

Failed to load remote gems: stack level too deep (SystemStackError)

11 votes

I have used RubyMine 3.2.1 trialversion for a week now, with no errors at all. But now, when I open RubyMine I get this:

failed to load remote gems

What can I do to fix it? I am using Ruby Version Manager as well.

spec_fetcher.rb:170: stack level too deep (SystemStackError)


EDIT: I am still getting this error!

Looks like some problem with the gem hosting servers, you will get the same behavior in the terminal:

% gem list --remote --all

*** REMOTE GEMS ***

/Users/denofevil/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/spec_fetcher.rb:170: stack level too deep (SystemStackError)  

In RubyMine you can disable these pop-ups in Settings | Notifications | Gem Manager, set to Ignore.

UPDATE: We've filed a bug for this problem to rubygems project.

UPDATE 2: The issue is resolved in RubyGems 1.8.6, run gem update --system to get the latest RubyGems version.

How to find out which modules are mixin for a class in Rails?

7 votes

I'm a new Ruby/Rails guy. Here's one question puzzling me:

Can we find the exact module lists mixin-ed for a class in Rails from the API doc? For example, if we have an instance of one subclass of ActiveRecord::Base, we can use validates method in this class such as following:

class Product < ActiveRecord::Base
  has_many :line_items
  validates :title, :description, :image_url, :presence => true
end

from rails api doc we can find that validates belongs to ActiveModel::Validations::ClassMethods, so ActiveRecore::Base must have ActiveModel::Validations::ClassMethods mixin, but I didn't find anything relating to this in the api reference. Can anyone tell me if I can find this info from api doc?

Thanks for all of your help in advance. I really hope my question doesn't sound too silly:)

I don't see anything like that in any of the Rails documentation I've seen:

And with monkey patching, there probably isn't any way to know until Rails is all cranked up and you have an actual ActiveRecord::Base in your hands; for example, the PostgreSQL, MySQL, and SQLite adapters re-open ActiveRecord::Base and they might include extra modules along the way; other gems you're using and even your own code may do similar things.

If you just want to know the standard set of mixins, use the source (Luke!) or do as maniek suggests and ask ActiveRecord::Base in the Rails console.

In general, the Rails API documentation isn't that useful unless you already know what you're looking for and even then, digging into the source is often necessary.

Your best bet is to check the guides for what you need and read the source if that doesn't work.


Short Answer: You can't get your list from the documentation because the modules cannot be known until run time. Read the guides and the source if you need to know something.

7 votes

I'm looking for a Sparse Matrix library I can use from Ruby. I'm currently using the GNU Scientific Library bindings provided by the "gsl" gem, but my application would be better optimized if I used a dedicated sparse matrix library. I've investigated the linalg and NArray libraries. None of the these three libraries support sparse-matrix optimised storage or operations.

Is there anything out there I've missed - or an existing C library that may be possible to write bindings for? I'd prefer the former to that latter, as I haven't written C bindings in Ruby before, but I would be willing to attempt it.

Pure ruby solutions are going to be ridiculously slow. I'd be tempted to pick up something like MTJ (http://code.google.com/p/matrix-toolkits-java/) and use it under JRuby.

There's a bunch of java code out there; much of it is pretty mature, although I don't know the space well enough to recommend a particular library. I can tell you that I've used java from jruby often and it's a joy to work with.

Is == a special method in Ruby?

6 votes

I understand that x == y in Ruby interpreted as a.==(y). I tried to check if I can achieve the same with custom method, foo, like this:

class Object
  def foo(n)
    self == n
  end
end

class A
  attr_accessor :x
end

a = A.new
a.x = 4

puts a.x.==(4)   # => true
puts a.x.foo(4)  # => true

puts a.x == 4    # => true
puts a.x foo 4   # => in `x': wrong number of arguments (1 for 0) (ArgumentError)

Unfortunately, this doesn't work. What am I missing ? Is == a special method in Ruby ?

No, == is not a special method in Ruby. It's a method like any other. What you are seeing is simply a parsing issue:

a.x foo 4

is the same as

a.x(foo(4))

IOW, you are passing foo(4) as an argument to x, but x doesn't take any arguments.

There is, however, special operator syntax, which allows you to write

a == b

instead of

a.== b

for a limited list of operators:

==
!=
<
>
<=
>=
<=>
===
&
|
*
/
+
-
%
**
>>
<<
!==
=~
!~

Also, there is special syntax that allows you to write

!a

and

~a

instead of

a.!

and

a.~

As well as

+a

and

-a

instead of

a.+@

and

a.-@

Then, there is

a[b]

and

a[b] = c

instead of

a.[] b

and

a.[]= b, c

and last but not least

a.(b)

instead of

a.call b

Ruby $stdout vs. STDOUT

6 votes

In Ruby, what is the difference between $stdout (preceded by a dollar sign) and STDOUT (in all caps)? When doing output redirection, which should be used and why? The same goes for $stderr and STDERR.

Edit: Just found a related question.

$stdout is a global variable that represents the current standard output. STDOUT is a constant representing standard output and is typically the default value of $stdout.

With STDOUT being a constant, you shouldn't re-define it, however, you can re-define $stdout without errors/warnings (re-defining STDOUT will raise a warning). for example, you can do:

$stdout = STDERR

Same goes for $stderr and STDOUT

Hope this helps.


So, to answer the other part of your question, use the global variables to redirect output, not the constants. Just be careful to change it back further on in your code, re-defining global variables can impact other parts of your application.

What's the preferred RDF toolset for Ruby?

6 votes

What's the best Ruby library for working with RDF and SPARQL? I saw some other related questions but they were over two years old.

Try RDF.rb (courtesy of Google).

Difference between <=> and == in Ruby?

6 votes

What are their differences? Coming from a Java background, it does seem to me <=> is the same as Java's equals(), while == is for direct reference comparison. Is this right?

== only measures if two objects are equal, whereas <=> should return -1 if the first object is smaller, 0 if they are equal, and 1 if the first object is greater.

If you define a <=> method for your class, you'll get all of the other comparison operators defined as well (==, <, >, and so on).

ruby - How to return from inside eval?

6 votes

I have a code which I need to use within eval. Sometimes I need to get out from the eval code, but my tries lead to errors.

E.g.:

# expected to see 1, 2 and 5; not 3 nor 4; and no errors
eval "puts 1; puts 2; return; puts 3; puts 4"   # => Error: unexpected return
puts 5

I tried with return, end, exit, break, and I couldn't get success. exit doesn't raise errors, but then I don't get the 5.

(Note: I know that eval is evil, but in this case I need to use it.)

Thank you all, but I found a solution which fits best into my problem:

lambda do
  eval "puts 1; puts 2; return; puts 3; puts 4"
end.call
puts 5

This way the intuitive return keyword can be used inside eval to get out from it successfully.

I didn't like the conditional-like solutions in this case because it would force me (or the user) to add an end at the end.

About using throw/catch or break, I consider the return keyword more intuitive.

What's the fastest way to build a string in Ruby?

5 votes

In Ternary operator, a person wanting to join ["foo", "bar", "baz"] with commas and and "and" cited The Ruby Cookbook as saying

If efficiency is important to you, don't build a new string when you can append items onto an existing string. [And so on]... Use str << var1 << ' ' << var2 instead.

But the book was written in 2006.

Is using appending (ie <<) still the fastest way to build a large string given an array of smaller strings, in all major implementations of Ruby?

Use Array#join when you can, and String#<< when you can't.

The problem with using String#+ is that it must create an intermediary (unwanted) string object, while String#<< mutates the original string. Here are the time results (in seconds) of joining 1,000 strings with ", " 1,000 times, via Array#join, String#+, and String#<<:

Ruby 1.9.2p180      user     system      total        real
Array#join      0.320000   0.000000   0.320000 (  0.330224)
String#+ 1      7.730000   0.200000   7.930000 (  8.373900)
String#+ 2      4.670000   0.600000   5.270000 (  5.546633)
String#<< 1     1.260000   0.010000   1.270000 (  1.315991)
String#<< 2     1.600000   0.020000   1.620000 (  1.793415)

JRuby 1.6.1         user     system      total        real
Array#join      0.185000   0.000000   0.185000 (  0.185000)
String#+ 1      9.118000   0.000000   9.118000 (  9.118000)
String#+ 2      4.544000   0.000000   4.544000 (  4.544000)
String#<< 1     0.865000   0.000000   0.865000 (  0.866000)
String#<< 2     0.852000   0.000000   0.852000 (  0.852000)

Ruby 1.8.7p334      user     system      total        real
Array#join      0.290000   0.010000   0.300000 (  0.305367)
String#+ 1      7.620000   0.060000   7.680000 (  7.682265)
String#+ 2      4.820000   0.130000   4.950000 (  4.957258)
String#<< 1     1.290000   0.010000   1.300000 (  1.304764)
String#<< 2     1.350000   0.010000   1.360000 (  1.347226)

Rubinius (head)     user     system      total        real
Array#join      0.864054   0.008001   0.872055 (  0.870757)
String#+ 1      9.636602   0.076005   9.712607 (  9.714820)
String#+ 2      6.456403   0.064004   6.520407 (  6.521633)
String#<< 1     2.196138   0.016001   2.212139 (  2.212564)
String#<< 2     2.176136   0.012001   2.188137 (  2.186298)

Here's the benchmarking code:

WORDS = (1..1000).map{ rand(10000).to_s }
N = 1000

require 'benchmark'
Benchmark.bmbm do |x|
  x.report("Array#join"){
    N.times{ s = WORDS.join(', ') }
  }
  x.report("String#+ 1"){
    N.times{
      s = WORDS.first
      WORDS[1..-1].each{ |w| s += ", "; s += w }
    }
  }
  x.report("String#+ 2"){
    N.times{
      s = WORDS.first
      WORDS[1..-1].each{ |w| s += ", " + w }
    }
  }
  x.report("String#<< 1"){
    N.times{
      s = WORDS.first.dup
      WORDS[1..-1].each{ |w| s << ", "; s << w }
    }
  }
  x.report("String#<< 2"){
    N.times{
      s = WORDS.first.dup
      WORDS[1..-1].each{ |w| s << ", " << w }
    }
  }
end

Results obtained on Ubuntu under RVM. Results from Ruby 1.9.2p180 from RubyInstaller on Windows are similar to the 1.9.2 shown above.

Ruby: Mail gem add \r\n after 60 chars in mail

5 votes

I want to port actionmailer_x509 to Rails 3. In order to do that I try to create Mail object from big string with signed email.

You can see such creation on this line: https://github.com/petRUShka/actionmailer_x509/blob/master/lib/actionmailer_x509.rb#L129

Original string (smime0): https://gist.github.com/1d2c84cc2e255be010a6

Resulted Mail object dumped to file(newm): https://gist.github.com/4682fe88e8dcfeca60b2

For example, you can see the difference between line 26 of smime0 and line 40 of newm. In smime0 \r\n is setted after each 64 chars, and in newm \r\n is setted after each 60 chars.

Such behaviour brokes signature. Is it possible to change this behaviour? I tried to find out how to turn off it, but was failed.

May be there is some other workaround for this point.

P.S. Mail gem: https://github.com/mikel/mail, thread with discussion about x509 and actionmailer: How do I send signed emails from ActionMailer in Rails 3?

The carriage returns shouldn't be a problem, because the parser will know that it's base64 encoded (and will discard \r\n).

I think the error comes from the Content-id. I see that in your mail samples, newm adds a Content-ID field, and it changes the signed message (try to remove the Content-ID line and verify the message).

Possible workarounds:

  • Fix the Mail gem to prevent it from adding a Content-ID
  • Add a Content-ID before signing, because Mail will keep it if it's present

Side effects of redefining $stdout and $stderr in a Rails app

5 votes

I'd like to temporarily redirect $stdout and $stderr to a file in a script that will be run by script/runner in a Rails app. Are there any potential side effects to doing so? Will changing the global variable cause the output streams to be redirected in other parts of the Rails application during the duration of my script? What about other libraries or threads used by the script?

The standard output and standard error streams are generally accessible in two ways each:

  • $stdout and STDOUT
  • $stderr and STDERR

A sufficiently clever person could also open their own copies using IO.new with a file descriptor argument:

sneaky = IO.new(2, 'w')

And now you have writable access to the standard error stream through sneaky without having anything to do with $stderr or STDERR.

Reassigning $stderr and $stdout should work fine unless something in your code, your gems, or Ruby itself is using the constants (STDOUT, STDERR) or is accessing the streams directly through C's stdio, unix's low level read/write with numeric file descriptors or is opening their own access to the streams using IO.new. I haven't dug into the source but I doubt assigning to $stdout will do anything to stdout in C-land or file descriptor 1 in Unix-land.

If you really need to trap the standard output and error streams then you're probably better off writing a wrapper shell script to redirect the streams for you.


UPDATE: If you're mostly (only?) concerned about changing $stdout and $stderr inside your script/runner bleeding into the rest of your Rails app then you don't have to worry about that. Each process — your script/runner process and however many server processes your main application has running — gets its own set of globals so you can change them all you want in your script without making a mess of your main application. Of course, you still have to worry about gems using STDOUT instead of $stderr or using IO.new to get their own private standard out.

5 votes

I'm not sure I understand this syntax error. I'm using Carrierwave to manage some file uploads in a Rails app, and I seem to be passing a block to one of the methods incorrectly.

Here's the example in the Carrierwave Docs:

version :thumb do
  process :resize_to_fill => [200,200]
end

Here's what I had:

version :full   { process(:resize_to_limit => [960, 960]) }
version :half   { process(:resize_to_limit => [470, 470]) }
version :third  { process(:resize_to_limit => [306, 306]) }
version :fourth { process(:resize_to_limit => [176, 176]) }

The above doesn't work, I get syntax error, unexpected '}', expecting keyword_end. Interestingly enough, the following works perfectly:

version :full   do process :resize_to_limit => [960, 960]; end
version :half   do process :resize_to_limit => [470, 470]; end
version :third  do process :resize_to_limit => [306, 306]; end
version :fourth do process :resize_to_limit => [176, 176]; end

So, my question is, why can I pass a block using do...end but not braces in this instance?

Thanks!

Try this:

version(:full)   { process(:resize_to_limit => [960, 960]) }
version(:half)   { process(:resize_to_limit => [470, 470]) }
version(:third)  { process(:resize_to_limit => [306, 306]) }
version(:fourth) { process(:resize_to_limit => [176, 176]) }

You have a precedence problem. The { } block binds tighter than a do...end block and tighter than a function call; the result is that Ruby thinks you're trying to supply a block as an argument to a symbol and says no.

You can see a clearer (?) or possibly more familar example by comparing the following:

[1, 2, 3].inject 0  { |x, y| x + y }
[1, 2, 3].inject(0) { |x, y| x + y }

How can I get Browser.text.include? to be case insensitive?

5 votes

It's as simple as that:

How can I get Browser.text.include?, or Ruby in general, to be case insensitive for that specified command?

One of the easiest ways is to downcase or upcase the text that you're reading:

Browser.text.downcase.include?

Then, you need to make sure that your desired text is supplied in all lowercase.

Ruby module given arguments calls a method?

5 votes

I'm confused about what's going on in the Nokogiri docs.

As far as I can tell, if

require 'nokogiri'
some_html = "<html><body><h1>Mr. Belvedere Fan Club</h1></body></html>"

then these three lines do the same thing:

html_doc = Nokogiri::HTML::Document.parse(some_html)
html_doc = Nokogiri::HTML.parse(some_html)
html_doc = Nokogiri::HTML(some_html)

The second is just a convenience method for the first. But to my non-Ruby eyes, the third looks like it's passing an argument to a module, not a method. I realize that Ruby has constructors, but I thought they took the form Class.new, not Module(args). What's going on here?

It's just syntax sugar, look at the Nokogiri::HTML module definition:

module Nokogiri
  class << self
    ###
    # Parse HTML.  Convenience method for Nokogiri::HTML::Document.parse
    def HTML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
      Nokogiri::HTML::Document.parse(thing, url, encoding, options, &block)
    end
  end

  module HTML
    class << self
      ###
      # Parse HTML.  Convenience method for Nokogiri::HTML::Document.parse
      def parse thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
        Document.parse(thing, url, encoding, options, &block)
      end

      ####
      # Parse a fragment from +string+ in to a NodeSet.
      def fragment string, encoding = nil
        HTML::DocumentFragment.parse string, encoding
      end
    end

    # Instance of Nokogiri::HTML::EntityLookup
    NamedCharacters = EntityLookup.new
  end
end

First, they define a class method at the Nokogiri module called HTML (yes, Ruby allows you to do that), then they define the module Nokogiri::HTML and in there they define the class method parse.

Most people don't know but the :: operator can also be used to perform method calls:

"my_string"::size #will print 9

A folder where to put "global" shared partial templates

3 votes

I am using Ruby on Rails 3.0.7 and I am planning to use partial templates. All classes in my application would use same partials so I have to decide where to located all those.

Is it a good idea to put "global" shared partial templates in the lib folder? If no, what is a common practice to choose the folder where to put those? Any advice on how to properly name and load that folder?

The standard is placing all shared partials in app/views/shared, and referencing them as

render :partial => 'shared/partial_name'

If you have a standard "row in a list" partial (say, for an index page), you could use a shared partial like:

# To render a single object row:
render :partial => 'shared/item', :locals => { :item => @item }
# Or to render them all:
render :partial => 'shared/item', :collection => @items

ruby parsing youtube url

3 votes

I've written a ruby youtube url parser. It's designed to take an input of a youtube url of one of the following structures (these are currently the youtube url structures that I could find, maybe there's more?):

http://youtu.be/sGE4HMvDe-Q
http://www.youtube.com/watch?v=Lp7E973zozc&feature=relmfu
http://www.youtube.com/p/A0C3C1D163BE880A?hl=en_US&#038;fs=1

The aim is to save just the id of the clip or playlist so that it can be embedded, so if it's a clip: 'sGE4HMvDe-Q', or if it's a playlist: 'p/A0C3C1D163BE880A'

The parser I wrote works fine for these urls, but seems a bit brittle and long-winded, I'm just wondering if someone could suggest a nicer ruby approach to this problem?

def parse_youtube
    a = url.split('//').last.split('/')
    b = a.last.split('watch?v=').last.split('?').first.split('&').first
    if a[1] == 'p'
        url = "p/#{b}"
    else
        url = b
    end
end

def parse_youtube url
   regex = /^(?:http:\/\/)(?:www\.)?\w*\.\w*\/(?:watch\?v=)?((?:p\/)?[\w\-]+)/
   url.match(regex)[1]
end

urls = %w[http://youtu.be/sGE4HMvDe-Q 
          http://www.youtube.com/watch?v=Lp7E973zozc&feature=relmfu
          http://www.youtube.com/p/A0C3C1D163BE880A?hl=en_US&fs=1]

urls.each {|url| puts parse_youtube url }
# sGE4HMvDe-Q
# Lp7E973zozc
# p/A0C3C1D163BE880A

Depending on how you use this, you might want a better validation that the URL is indeed from youtube.

Modelling Company and Person Customers in Rails

1 votes

My Rails application uses STI where I have different types of companies and persons. For example I have suppliers, manufacturers and customers as types of Company. I have also employees, contacts and customers as types of People.

Now I want to refer to a Customer which can either be a Company Customer or a Person Customer. Which method can I use/should I use to combine these two different entities into one? So I can refer to a Customer, from an Order?

You could either use:

Order      
   belongs_to :company
   belongs_to :person
end

And have two foreign keys - and then add some validations to make sure one of them is filled in, and then maybe add a 'customer' method which returns either the related company or person, depending which is used.

OR, create a separate Customer model (and table), which has those two same two foreign keys, and then Order can simply belong_to :customer. This second method may be preferably if you want to store additional data at the customer level (such as credit limit, or billing details), and may be cleaner long-term.

Alternative, you could reconsider your business logic, and insist that all orders belongs to a Person, even if that person is an employee of a Company and is purchasing on behalf of the company.

F