Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to make ERB marshalable #54

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions lib/erb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,28 @@ def self.version
VERSION
end

module Unmarshalable # :nodoc:
def initialize_for_marshal
@_init = self.class.singleton_class
end
private :initialize_for_marshal

def pre_eval_check
unless @_init.equal?(self.class.singleton_class)
raise ArgumentError, "not initialized"
end
end
private :pre_eval_check
end
include Unmarshalable

# Module to make ERB marshalable.
module Marshalable # :nodoc:
Unmarshalable.private_instance_methods.each do |m|
define_method(m) {}
end
end

#
# Constructs a new ERB object with the template specified in _str_.
#
Expand Down Expand Up @@ -351,7 +373,7 @@ def initialize(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eou
@src, @encoding, @frozen_string = *compiler.compile(str)
@filename = nil
@lineno = 0
@_init = self.class.singleton_class
initialize_for_marshal
end
NOT_GIVEN = Object.new
private_constant :NOT_GIVEN
Expand Down Expand Up @@ -423,9 +445,7 @@ def run(b=new_toplevel)
# code evaluation.
#
def result(b=new_toplevel)
unless @_init.equal?(self.class.singleton_class)
raise ArgumentError, "not initialized"
end
pre_eval_check
eval(@src, b, (@filename || '(erb)'), @lineno)
end

Expand Down
13 changes: 13 additions & 0 deletions test/erb/test_erb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,19 @@ def test_prohibited_marshal_load
assert_raise(ArgumentError) {erb.result}
end

class MarshalableERB < ERB
include Marshalable
end

def test_marshalable_subclass_marshal
erb = MarshalableERB.new("<%=x%>")
dump = assert_nothing_raised(TypeError) {Marshal.dump(erb)}
loaded = Marshal.load(dump)
bind = binding
bind.local_variable_set(:x, 42)
assert_equal("42", loaded.result(bind))
end

def test_multi_line_comment_lineno
erb = ERB.new(<<~EOS)
<%= __LINE__ %>
Expand Down