Skip to content
This repository
Browse code

stop subclassing string

  • Loading branch information...
commit 188cc90af9b29d5520564af7bd7bbcdc647953ca 1 parent e76ced0
Aaron Patterson authored June 21, 2012
13  actionpack/lib/action_view/template/resolver.rb
@@ -7,7 +7,7 @@ module ActionView
7 7
   # = Action View Resolver
8 8
   class Resolver
9 9
     # Keeps all information about view path and builds virtual path.
10  
-    class Path < String
  10
+    class Path
11 11
       attr_reader :name, :prefix, :partial, :virtual
12 12
       alias_method :partial?, :partial
13 13
 
@@ -19,9 +19,16 @@ def self.build(name, prefix, partial)
19 19
       end
20 20
 
21 21
       def initialize(name, prefix, partial, virtual)
22  
-        @name, @prefix, @partial = name, prefix, partial
23  
-        super(virtual)
  22
+        @name    = name
  23
+        @prefix  = prefix
  24
+        @partial = partial
  25
+        @virtual = virtual
24 26
       end
  27
+
  28
+      def to_str
  29
+        @virtual
  30
+      end
  31
+      alias :to_s :to_str
25 32
     end
26 33
 
27 34
     cattr_accessor :caching
2  actionpack/test/template/testing/null_resolver_test.rb
@@ -6,7 +6,7 @@ def test_should_return_template_for_any_path
6 6
     templates = resolver.find_all("path.erb", "arbitrary", false, {:locale => [], :formats => [:html], :handlers => []})
7 7
     assert_equal 1, templates.size, "expected one template"
8 8
     assert_equal "Template generated by Null Resolver", templates.first.source
9  
-    assert_equal "arbitrary/path.erb", templates.first.virtual_path
  9
+    assert_equal "arbitrary/path.erb", templates.first.virtual_path.to_s
10 10
     assert_equal [:html],          templates.first.formats
11 11
   end
12 12
 end

0 notes on commit 188cc90

Andrés Mejía

Just out of curiosity, why not define the to_s method directly instead of this alias?

Aaron Patterson

We probably could. I defined to_str because we need that in order to coerce to a string. e.g.:

irb(main):001:0> class Foo; def to_str; 'hello'; end end
=> nil
irb(main):002:0> class Bar; def to_s; 'hello'; end end
=> nil
irb(main):003:0> File.join('/', Foo.new)
=> "/hello"
irb(main):004:0> File.join('/', Bar.new)
TypeError: can't convert Bar into String
    from (irb):4:in `join'
    from (irb):4
    from /Users/aaron/.local/bin/irb:12:in `<main>'
irb(main):005:0>

I actually would rather not implement to_s.

Andrés Mejía

Got it. I didn't know about to_str and coercion. Thanks for the explanation!

Please sign in to comment.
Something went wrong with that request. Please try again.