yesh
yesh

Reputation: 2070

How to avoid multiple if/else

I am new to Rails, and I am trying to figure out a better way of doing this: I loaded some seed data into my database using a Rake task which reads from a YAML file.

Template.YAML:

- file_name:        Template1
  description:      temp1
  required_fields:  address

- file_name:        Template2
  description:      temp2 
  required_fields:  user_id,user_name

- file_name:        Template3
  description:      temp3
  required_fields:  user_id,address

In my view, I have a drop down where the user can select a template to load and, depending on the template he has selected, I need to show the text boxes to get the required fields to run the template.

Template.html.slim:

dt
 label for="template_name" Select The Template To Run
dd
 = select_tag :template_name,options_for_select(@template_seed_data_array.insert(0, "Please select the template")), :onchange => "Template.toggleRequiredFields(); return false"

#user_id style="display:none"
 dt
  label for="user_id" Enter User Id
 dd
   = text_field_tag :user_id, @template_library[:user_id]

#user_name style="display:none"
 dt
  label for="user_name" Enter user name
 dd
  = text_field_tag :user_name, @template_library[:user_name]
 .
 .
 .

In my coffescript, I do a bunch of if/else to hide and show these text boxes depending on what the user is selecting.

Template.coffee:

toggleRequiredFields: ->
  Template = $('#template_name').val()
  if Template in ['Template3','Template2']
    $('#user_id').show();
    .
    .
  else 
    $('#user_id').hide();  
    .
    . 

Over time, the number of templates gets higher and the if/else logic gets messy. Is there a better way of doing this hide/show toggle when a template is selected by the user?

Upvotes: 1

Views: 191

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187312

If you expose that Template.YAML file as JSON to the client, this should be easy.

Add a JSON dump of the templates data in a JavaScript tag in the view:

:javascript
  var templates = #{@templates.to_json};

Then write some code to read from it:

:coffeescript
  template = null
  templateName = $('#template_name').val()

  # Find the proper template configuration
  for templateConfig in templates
    if templateName == template.file_name
      template = templateConfig # found it!

  # Hide all fields.
  $('form input').hide() # or whatever selects everything you want to hide

  # Show just the fields we need.
  for fieldID in template.required_fields
    $("##{ fieldID }").show()

From here you can add dozens of entries to your template config file, or change around what fields are shown, and you won't have to change the code at all.

Upvotes: 1

Related Questions