Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
977 views
in Technique[技术] by (71.8m points)

ruby inside javascript block [slim template]

There is a way to put ruby conditions inside javascript block? i.e.

javascript:
  var config = {
      common_value_1 : 1, 
      common_value_2 : 2 
  };
  - if my_value === true # this must be a ruby condition
    config.custom_true_value_1 = "1" ;
    config.custom_true_value_2 = "#{my_value}" ;
  - else
    config.custom_false_value_1 = "1" ;
    config.custom_false_value_2 = "#{my_value}" ;

Or is there another workaround at this problem? Because the ugly way that I can use its:

javascript:
    var config = {
      common_value_1 : 1, 
      common_value_2 : 2 
    };
- if my_value === true # this must be a ruby condition
  javascript:
    config.custom_true_value_1 = "1" ;
    config.custom_true_value_2 = "#{my_value}" ;
- else
  javascript:
    config.custom_false_value_1 = "1" ;
    config.custom_false_value_2 = "#{my_value}" ;

But I don't like it because if config has common values between if and else then I would duplicate my code and would be much larger and hard to maintain.

Updated with better examples

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a style similar to string interpolation. See example below.

javascript:
  var config = { 
    custom: "#{my_value ? 'truthy' : 'falsy'}",
    current_user: #{raw current_user.to_json}
  };

** Update below **

If you want more advanced configuration I would recommend to create a class, for example

class ClientConfig
  attr_accessor :foo, :bar

  # .. code

  def to_json
    { foo: foo, bar: bar }.to_json
  end
end

# in view file
javascript: 
  var config = ClientConfig.new.to_json

Else you also have the opportunity to create a ruby partial I've created an example below who may not be so beautiful but I works.

# template_path/_config.html.ruby
def configuration
  { foo: "Hello", bar: "World" }
end

def july_special
  { june_key: "It's June" }
end

def month_name
  Date.today.strftime("%B")
end

config = month_name == 'July' ? configuration.merge(july_special) : configuration

content_tag :script, config.to_json.html_safe

# viewfile
= render 'template_path/config'

So my point is that there are multiple ways of doing this and you should try to find the way the one that suits you and your application the most. In my case, I would use my first example (before the update) if I just need one or two values else I would go for the class ClientConfig.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...